<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Deliverorder_m extends CI_Model {
    function __construct()
    {
        parent::__construct();
    }
    //e邮宝线上 cnpost  eBay 亚太物流平台 API V4.0.0 说明文档
    public function getcnpostExpress(){


        if($this->config->item("cnpostexpressset")){
                $ems = stripslashes($this->config->item("cnpostexpressset"));
                $arr_ems = unserialize($ems);
                //暂时先测试  云途交运相关参数
                //$url = $arr_ems['cnpost_url'];
                //$version = $arr_ems['cnpost_version'];
                //$apiToken = $arr_ems['cnpost_token'];
            }else{
                echo "未正常获得到cnpost接1口，请在订单相关设置中检查是否正确！";
                exit;
            }
        //交运
        $where  = "isexe = 0 AND orderType =11";
        $this->db->where($where);
        $total = $this->db->count_all_results('db_mabangorder');
        if($total==0)
        {
            echo "交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/11 \">";
            die;
        }
        $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =11 ORDER BY id DESC");
        $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
        $goodslist = $this->db->get_where('db_order_sell',"order_id ='".$orderID["order_id"]."'"." ORDER BY rec_id DESC ")->result_array();
        //print_r($goodslist);exit;
         //根据店铺shopid获取相关授权信息
        $sql = "SELECT * FROM d_shop WHERE id = '{$orderID['shopid']}' ";
        $rs_row = $this->db->query($sql)->row_array();
        //店铺判断
        if($rs_row['name']=="ebay-LC"){
            $rs_row['name']="lovelycostume";
        }
        if($rs_row['name']=="ebay-LP"){
            $rs_row['name']="lovelyplaza";
        }
        if($rs_row['name']=="ebay-CC"){
            $rs_row['name']="coscart";
        }
        if($rs_row['name']=="Cosstyle2014"){
            $rs_row['name']="cosplaystyle2014";
        }
        if($rs_row['name']=="ebay-greatitemzone"){
            $rs_row['name']="greatitemzone";
        }
        if($rs_row['name']=="ebay-holydad"){
            $rs_row['name']="holydad";
        }
        if($rs_row['name']=="ebay-skyshow"){
            $rs_row['name']="skyshow";
        }
        if($rs_row['name']=="ebay-cossky"){
            $rs_row['name']="cossky";
        }
        if($rs_row['name']=="ebay-newlywonder"){
            $rs_row['name']="newlywonder";
        }
        //本地执行相关操作
        if(!empty($rs_row['amazonkey'])){
            $arr_auth = (array) json_decode($rs_row['amazonkey']);
        }else{
            echo "确认是否为Ebay店铺！不存在授权信息";
            exit;
        }
        //判断是否远程代理访问
        /**
        if(isset($rs_row['agent_visit'])&&$rs_row['agent_visit']==1){
            $this->remoteDB = $this->load->database('amazondata',TRUE);
            $sql_remote = "SELECT * FROM db_ebay_cnpost WHERE orderID = '{$rsdb['orderID']}' ";
            $rs_remote  = $this->remoteDB->query($sql_remote)->row_array();
            $rsdb['shopid'] = $rs_row['id'];
            if(!$rs_remote){
                $this->remoteDB->insert('db_ebay_cnpost',$rsdb);
            }else{
                $this->remoteDB->update('db_ebay_cnpost',$rsdb,'id='.$rs_remote['id']);
            }
            $this->db->update('db_mabangorder',array('isexe'=>2,'exememo'=>'请耐心等待远程主机交运')," orderID='".$rsdb['orderID']."'");
            //echo "远程主机会交运该订单!";exit;
            $str = "远程主机会交运该订单!";
            return array('str'=>$str);  //交运下一条数据
        }**/
        //soap请求
        //组 Application Key 由三个 ID 组成， DevID, AppID, CertID，分别对应于 eBay 物流平台的请求中的
        //APIDevUserID，AppID， CertID。具体请参考第四部分接口说明。
        /**
        $arr_order['AppID'] = "wangmx-testapp-SBX-0dbc19de5-274f9009"; //(Client ID)  AppID
        //$arr_order['APIPassword'] = "112358wang$"; //Password
        $arr_order['APIDevUserID'] = "34177b3a-e131-4f11-a722-6054548b7e64";   //APIDevUserID
        $arr_order['AppCert'] = "SBX-dbc19de5a5a1-1507-4646-81d5-55f0"; //(Client Secret)  AppCert
        $arr_order['Version']="4.0.0";
        $arr_order['APISellerUserID'] = "TESTUSER_fuman"; //cownsfia@126.com 630637979@qq.com
        $arr_order['APISellerUserToken'] = "AgAAAA**AQAAAA**aAAAAA**sSZTWQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4GkC5iDpwudj6x9nY+seQ**9DQEAA**AAMAAA**SlKWrMsys1Wa+Dsf0NMwlj8Fkzwq6Azylgs+cIzb9Z5Q6rKzxlFwABrhJZMYPpW8pnwswVrejRCgUD9Dfc4mFJhQvLy8shKGD5hX9lg1nYZ8c9dNH8R76xGrNxvktg2uFzHJmugvBH+n/CMSS9/oOzHIywO0doB5ugZXBSxjdLO0zUslwhLxKG8YbRkQXmAdL81/y/5gypFpH1qKIvDv2TMcmmpJsZbkUMWI5nJhAYkrb/KDkHVpTshqtqUkEVZu2Q4H27TrJO7XnKeqf4SRYQOeCHfivIkgglugXkHCsoY+dl6x1bc18s2VUA+ijSJRPVGNQWx75DO1cmDL/Zn/zv/VmHu3II6nK8ZLEaA/QZEKwPBNk6VPXFFtNo7K2bNadG9og6CZkpnKiGHMKY7P2kK2FltgRvnu7iIdLU7XWKuG3+GeQSITFZEdxqbmJt0wsNaT5MiXn4f4F7mRaC+Jaj5vENyt+DUUpurAaOcH3Xop0dtj66Eko+ZE6IU1wkYU40KEkxbgFpGl3Ew2XmFNt9DCINxffphkTX9MSelt9zPbldq/PfmX8e1BjXcntIahb5SPgJ9juPyYo6m2w6uqN2eyKy22uJbSUK+NUL+w6UBu1NCVWASMmtr1LvBBz4GNWdeu1Qcw8XlEfqKe1wDnmAKHmmXT1KJKjMkAdWzY7UpiZuX5VZuo8OIi7mTdXty37khEdsPNgOqxUVbHbK6UZ+dtd+pCsl0q1ikyny8uc5jP/n65v57mutNj3B9PCVPx";
        **/
        //正式账号
        //$arr_order['AppID'] = "wangmx-testapp-PRD-e090b840d-89555470"; //(Client ID)  AppID
        //$arr_order['APIDevUserID'] = "34177b3a-e131-4f11-a722-6054548b7e64";   //APIDevUserID
        //$arr_order['AppCert'] = "PRD-090b840d1bb0-4b74-4534-b407-d163"; //(Client Secret)  AppCert
        $arr_order['AppID']=$arr_auth['ebayappid'];
        $arr_order['APIDevUserID']=$arr_auth['ebaydevid'];
        $arr_order['AppCert']=$arr_auth['ebaycertid'];
        $arr_order['Version']="4.0.0";
        //$arr_order['APISellerUserID'] = "adorablestore";
        $arr_order['APISellerUserID'] = $rs_row['name'];
        //$arr_order['APISellerUserToken'] = "AgAAAA**AQAAAA**aAAAAA**JdYjWQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AAkouoDpaBpQqdj6x9nY+seQ**3MADAA**AAMAAA**4mhgMgjmdgRr4s2igqrrTQ8gP3vgylU9moOCINfKJDMjwaQvITDWwXMQ7yxCODZhuk7L+h+YvP777FBlDpfBjGynIdPgtL33hyH9bv73qjCRT3ULkX0BQISVv1ubFd4YUBx810ZwcmTJ/zxVZRkCP1QwttQ5iFbZBCkguwxBFOm/C4/Vedxi5zwFZuZ8lJVCOS8WsiRD5+AhE6F19BIMhuw5sYoKTjhWWfGqMhxaGZsEejPpZp2IIZmu4Ao/GM/6p8j1gEU6+3bIakiOPoav/ZiJ3IeXDK9xmOgZayEBvukF4bxWFgItQDe5ADYyQmO2QikQmdkw8rca2QthRM4AG4HyQT1GkNwURZzjWjHMpsjmq0Cmg8K3zh/h7c0K5dwg9+lp0ECQY9Yg52Oc2acezJZOZZCGYfWigJXK7+GNuRMOlq5qfjugyOpZQy8aVM71pIx0TMccjfly2oJD2wFrUVO4yYwyL2CzQow+fBGBqeagvYf+R55i1xP/642jdN6lbCjh8zMSmEcb8n1Ie4z9+O4Sx06JeaXpeqvsQaArkcJd3YuHGTGqaQWHKg+JjRSXTGGcHFtWdYaULumxcpwo8WAP8JKc7izceXGGPsaH7kaqltlD69dDbfom4SoZ95ymKJWQqowtY/8l3TYK9Yi0CcUURGY609etl6VkUcvWDYUkS6FquWEsYqMjPVoiTDGj0fNAGrxbj/OaxoWZSlQJDyEzeaU5FQQ6geb9kQt7EmCocQyMdedGlSeK8WJTF/hk";
        $arr_order['APISellerUserToken'] = $arr_auth['ebayusertoken'];
        $arr_order['Carrier'] = "CNPOST"; //可用值：CNPOST UBI  DHL eCommerce
        $arr_order['Service'] = "EPACK"; //可选
        $arr_order['MessageID'] = ""; //可选

        $arr_order['OrderDetail']['EMSPickUpType'] = 0; //0 - 上门揽收  1 - 卖家自送
        $arr_order['OrderDetail']['DropOffLocation'] = "SHA"; //可选 SHA – 上海

        //揽收地址信息  国际 e 邮宝的订单必须使用中文 地址。
        $arr_order['OrderDetail']['PickUpAddress']['Contact'] = $arr_ems['cnpost_username'];
        $arr_order['OrderDetail']['PickUpAddress']['Company'] = ""; //可选
        $arr_order['OrderDetail']['PickUpAddress']['Street'] = $arr_ems['cnpost_cnaddress'];
        $arr_order['OrderDetail']['PickUpAddress']['District'] = $arr_ems['cnpost_area']; //社区
        $arr_order['OrderDetail']['PickUpAddress']['City'] = $arr_ems['cnpost_city'];
        $arr_order['OrderDetail']['PickUpAddress']['Province'] = $arr_ems['cnpost_province'];
        $arr_order['OrderDetail']['PickUpAddress']['Postcode'] = $arr_ems['cnpost_postcode'];//可选
        $arr_order['OrderDetail']['PickUpAddress']['CountryCode'] = $arr_ems['cnpost_countrycode'];
        $arr_order['OrderDetail']['PickUpAddress']['Mobile'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['PickUpAddress']['Phone'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['PickUpAddress']['Email'] = $arr_ems['cnpost_email'];
        //寄件人地址 必须以英文填写
        $arr_order['OrderDetail']['ShipFromAddress']['Contact'] = $arr_ems['cnpost_username'];
        $arr_order['OrderDetail']['ShipFromAddress']['Company'] = ""; //可选
        $arr_order['OrderDetail']['ShipFromAddress']['Street'] = $arr_ems['cnpost_enaddress'];
        $arr_order['OrderDetail']['ShipFromAddress']['District'] = $arr_ems['cnpost_area'];
        $arr_order['OrderDetail']['ShipFromAddress']['City'] = $arr_ems['cnpost_city'];
        $arr_order['OrderDetail']['ShipFromAddress']['Province'] = $arr_ems['cnpost_province'];
        $arr_order['OrderDetail']['ShipFromAddress']['Postcode'] = $arr_ems['cnpost_postcode']; //可选
        $arr_order['OrderDetail']['ShipFromAddress']['CountryCode'] = $arr_ems['cnpost_countrycode'];
        $arr_order['OrderDetail']['ShipFromAddress']['Mobile'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['ShipFromAddress']['Phone'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['ShipFromAddress']['Email'] = $arr_ems['cnpost_email'];
        //收件人地址信息， 支持英语及俄语。
        $arr_order['OrderDetail']['ShipToAddress']['Contact'] = $orderID['consignee'];
        $arr_order['OrderDetail']['ShipToAddress']['Company'] = "";//可选
        $arr_order['OrderDetail']['ShipToAddress']['Street'] = $rsdb['customeraddress'];
        $arr_order['OrderDetail']['ShipToAddress']['District'] = $rsdb['customeraddress'];
        $arr_order['OrderDetail']['ShipToAddress']['City'] = $rsdb['customercity'];
        $arr_order['OrderDetail']['ShipToAddress']['Province'] = $rsdb['customerprovince'];
        $arr_order['OrderDetail']['ShipToAddress']['Postcode'] = $rsdb['customerzipcode']; //必填
        $arr_order['OrderDetail']['ShipToAddress']['CountryCode'] = $rsdb['customerqq'];
        $arr_order['OrderDetail']['ShipToAddress']['Mobile'] = $rsdb['customertel1'];
        $arr_order['OrderDetail']['ShipToAddress']['Phone'] = isset($rsdb['customertel2'])?$rsdb['customertel2']:$rsdb['customertel1'];
        $arr_order['OrderDetail']['ShipToAddress']['Email'] = !empty($orderID['paypalmail'])?$orderID['paypalmail']:$orderID['email'];
        //退货地址信息，对国际 e 邮宝，请填写中文地址并且必须保持与寄件人地址是中英文翻译的关系
        $arr_order['OrderDetail']['ReturnAddress']['Contact'] = $arr_ems['cnpost_username'];
        $arr_order['OrderDetail']['ReturnAddress']['Company'] = "";//可选
        $arr_order['OrderDetail']['ReturnAddress']['Street'] = $arr_ems['cnpost_cnaddress'];
        $arr_order['OrderDetail']['ReturnAddress']['District'] = $arr_ems['cnpost_area'];
        $arr_order['OrderDetail']['ReturnAddress']['City'] = $arr_ems['cnpost_city'];
        $arr_order['OrderDetail']['ReturnAddress']['Province'] = $arr_ems['cnpost_province'];
        $arr_order['OrderDetail']['ReturnAddress']['Postcode'] = $arr_ems['cnpost_postcode']; //必填 对于无邮编的地区，比如香港，可留空。
        $arr_order['OrderDetail']['ReturnAddress']['CountryCode'] = $arr_ems['cnpost_countrycode'];
        $arr_order['OrderDetail']['ReturnAddress']['Mobile'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['ReturnAddress']['Phone'] = $arr_ems['cnpost_phone'];
        $arr_order['OrderDetail']['ReturnAddress']['Email'] = $arr_ems['cnpost_email'];
        //包裹信息
        $arr_order['OrderDetail']['ShippingPackage']['Description'] = "";//可选 60 字符
        $arr_order['OrderDetail']['ShippingPackage']['Length'] = "";//可选 包裹长度（米）
        $arr_order['OrderDetail']['ShippingPackage']['Width'] = "";//可选
        $arr_order['OrderDetail']['ShippingPackage']['Height'] = "";//可选
        $arr_order['OrderDetail']['ShippingPackage']['Incoterms'] = "";//可选 DDP(卖家承担关税) DDU(买家承担关税)
        $arr_order['OrderDetail']['ShippingPackage']['CollectionInstructions'] = "";//可选
        $arr_order['OrderDetail']['ShippingPackage']['DeliveryInstructions'] = ""; //可选
        //货品信息 目前一个商品测试一个
        foreach($goodslist as $key=>$value){
            $arr_order['OrderDetail']['ItemList']['Item']['EBayItemID'] = $value['product_link'];  //eBay 物品号
            $arr_order['OrderDetail']['ItemList']['Item']['EBayTransactionID'] = $orderID['order_sn']; //eBay 交易号
            $arr_order['OrderDetail']['ItemList']['Item']['EBayBuyerID'] = $orderID['customerid']; //eBay 买家 ID
            $arr_order['OrderDetail']['ItemList']['Item']['EBayItemTitle'] = ""; //可选  eBay 商品标题
            $arr_order['OrderDetail']['ItemList']['Item']['EBayEmail'] = ""; //可选  买家 eBay 电邮
            $arr_order['OrderDetail']['ItemList']['Item']['SoldQTY'] = $value['goods_number'];  //可选  卖出数量
            $arr_order['OrderDetail']['ItemList']['Item']['PostedQTY'] = $value['goods_number']; //必填  寄货数量，不能为 0
            $arr_order['OrderDetail']['ItemList']['Item']['SalesRecordNumber'] = ""; //可选
            $arr_order['OrderDetail']['ItemList']['Item']['OrderSalesRecordNumber'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['OrderID'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['ReceivedAmount'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['PaymentDate'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['SoldPrice'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['SoldDate'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['CurrencyCode'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['EBayMessage'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['PayPalEmail'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['PayPalMessage'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['Note'] = "";//可选

            $arr_order['OrderDetail']['ItemList']['Item']['EBaySiteID'] = "12";//

            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['SKUID'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['DeclaredValue'] = 15;
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['Weight'] = 0.5;//物品重量（千克） 国际 e 邮宝包裹可用值 0-2
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['CustomsTitle'] = "周边小商品"; //国际 e 邮宝包裹请填中文报关名
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['CustomsTitleEN'] = "2015";
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['OriginCountryCode'] = "CN";
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['OriginCountryName'] = "China";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['HTSNumber'] = "";//可选
            $arr_order['OrderDetail']['ItemList']['Item']['SKU']['ExternalRefId'] = "";//可选
        }
        //发送请求  数组请求样式
           //print_r($soapclient->CancelAPACShippingPackage(array('CancelAPACShippingPackageRequest' => array('TrackCode' => "LK042013892CN"))));
            //$url = "https://apacshipping.sandbox.ebay.com.hk/aspapi/v4/ApacShippingService?wsdl";
            $url = "https://api.apacshipping.ebay.com.hk/aspapi/v4/ApacShippingService?wsdl"; //正式地址
            $client = new SoapClient($url);
            $post_data = array("AddAPACShippingPackageRequest"=>$arr_order);
            $rs = (array) $client->AddAPACShippingPackage($post_data);
            //$ceshi_cancel = $client->CancelAPACShippingPackage($post_data);
            //print_r($ceshi_cancel);exit;
          //$ceshi = "stdClass Object ( [AddAPACShippingPackageResult] => stdClass Object ( [Version] => 4.0.0 [Ack] => Success [Message] => AddAPACShippingPackage succeeded [Timestamp] => 2017-07-04T23:29:02.749-07:00 [InvocationID] => AA14B3A57E3B4493A87C527F6C8DEEBC [TrackCode] => LK289585774CN ) ) ";
          //$ceshi = $ceshi->AddAPACShippingPackageResult['TrackCode'];
        //返回值处理  交运单号 应该判断[Ack] => Failure 是否成功或失败
        if(isset($rs['AddAPACShippingPackageResult']->Ack)&&$rs['AddAPACShippingPackageResult']->Ack=="Success"){

            //new add 2017/7/26 确认提交到物流商系统中
            $arr_check['AppID']=$arr_auth['ebayappid'];
            $arr_check['APIDevUserID']=$arr_auth['ebaydevid'];
            $arr_check['AppCert']=$arr_auth['ebaycertid'];
            $arr_check['Version']="4.0.0";
            $arr_check['APISellerUserID'] = $rs_row['name'];
            $arr_check['APISellerUserToken'] = $arr_auth['ebayusertoken'];
            $arr_check['Carrier'] = "CNPOST"; //可用值：CNPOST UBI  DHL eCommerce
            //$arr_check['Service'] = "EPACK"; //可选
            $arr_check['MessageID'] = ""; //可选

            $arr_check['TrackCode'] = $rs['AddAPACShippingPackageResult']->TrackCode; //Required
            $arr_check['PickUpRequestDateTime'] = ""; //可选
            $p_data = array("ConfirmAPACShippingPackageRequest"=>$arr_check);
            $results = (array) $client->ConfirmAPACShippingPackage($p_data);
            if(isset($results['ConfirmAPACShippingPackageResult']->Ack)&&$results['ConfirmAPACShippingPackageResult']->Ack=="Success"){
                $arr_post_data["isexe"] = 1;
                $arr_post_data['exememo'] = '交运成功';
            }else{
                $reasonMessage = isset($results['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Message)?$results['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Message:""; //获取返回的错误信息
                //更新马帮表
                $exememo = '交运失败';
                $arr_post_data["isexe"] = 3; //等待二次交运cnpost
                $exememo.='<br>'.$reasonMessage;
                $arr_post_data['exememo'] = $exememo;
            }
            //new add end 7/26
            $arr_post_data['mailNo'] = $rs['AddAPACShippingPackageResult']->TrackCode; //运单号
            //$arr_post_data['mailNo'] = "LK289585774CN"; //运单号  测试 LK289647567CN 对应订单号1773531783011
            //$arr_post_data["isexe"] = 1;
            $arr_post_data["originCode"] = 0;
            $arr_post_data["destCode"] = 0;

            //测试
            //正式账号
            $arr_account['AppID'] = $arr_auth['ebayappid']; //(Client ID)  AppID
            $arr_account['APIDevUserID'] = $arr_auth['ebaydevid'];   //APIDevUserID
            $arr_account['AppCert'] = $arr_auth['ebaycertid']; //(Client Secret)  AppCert
            $arr_account['Version']="4.0.0";
            $arr_account['APISellerUserID'] = $rs_row['name']; //店铺名
            $arr_account['APISellerUserToken'] = $arr_auth['ebayusertoken'];
            $arr_account['Carrier'] = "CNPOST"; //可用值：CNPOST UBI  DHL eCommerce
            //new add
            $arr_account['TrackCode'] = $arr_post_data['mailNo'];
            $arr_account['PageSize'] = 1;//标签格式，可用值 0 - 适用于打印 A4 格式标签 1 – 适用于打印 4 寸 的热敏标签纸格 式标签
            $arr_account['MessageID'] = "";
            //标签地址
            $client = new SoapClient($url,
                array(
                    'trace' => 1,
                    'stream_context' => stream_context_create(
                        array(
                            'http' => array(
                                'protocol_version' => 1.0,
                            ),
                        )
                    ),
                )
            );
            $post_label = array('GetAPACShippingLabelRequest'=>$arr_account);
            $label_url = (array) $client->GetAPACShippingLabel($post_label);
            //print_r($label_url);exit;
            if($label_url['GetAPACShippingLabelResult']->Ack=="Success"){
                $label_pdf_content = $label_url['GetAPACShippingLabelResult']->Label;
                $dir = dirname(__FILE__) . "/../../uploads/cnpostexpress/".date("Ymd");
                !is_dir($dir) && @mkdir($dir, 0755, true);
                $Path_mailNo = $dir. "/".$arr_post_data['mailNo']."_mailno.pdf";
                //对获取的pdf流进行处理 标签
                //$content=file_get_contents($label_content); //返回的就是pdf流
                if(file_put_contents($Path_mailNo, $label_pdf_content)>0){
                    $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                    $rsdbts = $this->pdf2png($Path_mailNo,"cnpostexpress"); //转为对应目录下存储
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    //可能不止一张图片
                    if(!empty($rsdbts[0])){
                        $image_urls=implode(",",$rsdbts);
                        // $arr_post_data["print_img"] = $image_urls;
                    }else{
                        //$arr_post_data["print_img"] = $rsdbts[0];
                        $image_urls = $rsdbts[0];
                    }
                }
                $arr_post_data["print_img"] = $image_urls;
            }

            //var_dump($arr_body_express);exit;
            $update_order = "";
            $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
            $update_order["shipping_time"] = time();				//交运时间
            //$update_order["shipping_name"] = "UPS";
//            if($rsdb['deliver']=="EPACK"){
//                $update_order["shipping_name"] = "E邮宝";
//            }else{
//                $update_order["shipping_name"] = $rsdb['deliver'];
//            }
            $update_order["shipping_name"] = "E邮宝";
            $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='E邮宝'");
            $update_order["shipping_id"] = $shipping["id"];
            //$update_order["shipping_expectfee"] = ""; 需要通过计算
            $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
            //var_dump($arr_body_express);exit;
            //更新日志记录
			$imgdata = "";
            $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
            $imgdata["updatetime"] = date("Y-m-d H:i:s");
            $imgdata["createUid"] = $_COOKIE['userid'];
            $imgdata["types"] = 3;
            $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid'].",运单号：".$update_order["shipping_number"];
            $imgdata["createUser"] =$_COOKIE['username'];
            $this->db->insert('db_goods_log', $imgdata);

        }else{
            //判断交运失败的时候，是否存在运单号以及相关的pdf文档
            $code = isset($rs['AddAPACShippingPackageResult']->NotificationList->Notification->Code)?$rs['AddAPACShippingPackageResult']->NotificationList->Notification->Code:"";
           //Invalid item property (Item withItemId: [] TransactionId: [] recordAlready exists : )
            if($code=="E16"){
                //正式账号
                $url = "https://apacshipping.sandbox.ebay.com.hk/aspapi/v4/ApacShippingService?wsdl";
                $arr_account['AppID'] = $arr_auth['ebayappid']; //(Client ID)  AppID
                $arr_account['APIDevUserID'] = $arr_auth['ebaydevid'];   //APIDevUserID
                $arr_account['AppCert'] = $arr_auth['ebaycertid']; //(Client Secret)  AppCert
                $arr_account['Version']="4.0.0";
                $arr_account['APISellerUserID'] = $rs_row['name']; //店铺名
                $arr_account['APISellerUserToken'] = $arr_auth['ebayusertoken'];
                $arr_account['Carrier'] = "CNPOST"; //可用值：CNPOST UBI  DHL eCommerce
                $arr_account['EBayItemID'] = $arr_order['OrderDetail']['ItemList']['Item']['EBayItemID'];
                $arr_account['EBayTransactionID'] = $arr_order['OrderDetail']['ItemList']['Item']['EBayTransactionID'];
                $arr_account['MessageID'] = "";
                //标签地址
                $client = new SoapClient($url,
                    array(
                        'trace' => 1,
                        'stream_context' => stream_context_create(
                            array(
                                'http' => array(
                                    'protocol_version' => 1.0,
                                ),
                            )
                        ),
                    )
                );
                $post_label = array('GetAPACShippingTrackCodeRequest'=>$arr_account);
                $deliverNumber_url = (array) $client->GetAPACShippingTrackCode($post_label);
                //获取运单号
                if($deliverNumber_url['GetAPACShippingTrackCodeResult']->Ack=="Success"){
                    //正式账号
                    foreach($arr_account as $key=>$value){
                        if($key=="EBayItemID" || $key=="EBayTransactionID" ){
                            unset($arr_account[$key]);
                        }
                    }
                    $arr_account['TrackCode'] = $deliverNumber_url['GetAPACShippingTrackCodeResult']->TrackCode;
                    $arr_account['PageSize'] = 1;
                    $post_label = array('GetAPACShippingLabelRequest'=>$arr_account);
                    $label_url = (array) $client->GetAPACShippingLabel($post_label);
                    //print_r($label_url);exit;
                    if($label_url['GetAPACShippingLabelResult']->Ack=="Success"){
                        $label_pdf_content = $label_url['GetAPACShippingLabelResult']->Label;
                        $dir = dirname(__FILE__) . "/../../uploads/cnpostexpress/".date("Ymd");
                        !is_dir($dir) && @mkdir($dir, 0755, true);
                        $Path_mailNo = $dir. "/".$deliverNumber_url['GetAPACShippingTrackCodeResult']->TrackCode."_mailno.pdf";
                        //对获取的pdf流进行处理 标签
                        //$content=file_get_contents($label_content); //返回的就是pdf流
                        if(file_put_contents($Path_mailNo, $label_pdf_content)>0){
                            $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                            $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                            //实现pdf转换为png图片格式 放到线上做测试
                            $rsdbts = $this->pdf2png($Path_mailNo,"cnpostexpress"); //转为对应目录下存储
                            //$arr_post_data["print_img"] = $rsdbts[0];
                            //可能不止一张图片
                            if(!empty($rsdbts[0])){
                                $image_urls=implode(",",$rsdbts);
                                // $arr_post_data["print_img"] = $image_urls;
                            }else{
                                //$arr_post_data["print_img"] = $rsdbts[0];
                                $image_urls = $rsdbts[0];
                            }
                        }
                        $arr_post_data["print_img"] = $image_urls;
                    }
                }
                $arr_post_data['exememo'] = '交运成功';
                $arr_post_data['mailNo'] = $deliverNumber_url['GetAPACShippingTrackCodeResult']->TrackCode; //运单号
                //$arr_post_data['mailNo'] = "LK289585774CN"; //运单号  测试 LK289647567CN 对应订单号1773531783011
                $arr_post_data["isexe"] = 1;
                $arr_post_data["originCode"] = 0;
                $arr_post_data["destCode"] = 0;
                //var_dump($arr_body_express);exit;
                $update_order = "";
                $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
                $update_order["shipping_time"] = time();				//交运时间
                $update_order["shipping_name"] = "E邮宝";
                $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='E邮宝'");
                $update_order["shipping_id"] = $shipping["id"];
                $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
                //更新日志记录
				$imgdata="";
                $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '重复交运获取运单号成功,交易ID='.$orderID['tradeid'].",运单号：".$update_order["shipping_number"];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
            }else{
                $reasonMessage = isset($rs['AddAPACShippingPackageResult']->NotificationList->Notification->Message)?$rs['AddAPACShippingPackageResult']->NotificationList->Notification->Message:""; //获取返回的错误信息
                //更新马帮表
                $exememo = '交运失败';
                $arr_post_data["isexe"] = 2;
                $exememo.='<br>'.$reasonMessage;
                $arr_post_data['exememo'] = $exememo;
                // echo $reasonMessage;exit;
            }

        }
        $arr_post_data["mailinstime"] =time();
        $this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
        $str = $rsdb["orderID"].$exememo;
        return array('str'=>$str);
    }
    //二次交运cnpost
    public function getsecondcnpostExpress(){
        //cnpost 二次交运 isexe = 3
        $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 3 AND orderType =11 ORDER BY id DESC");
        //交运
        /**
        $where  = "isexe = 3 AND orderType =11";
        $this->db->where($where);
        $total = $this->db->count_all_results('db_mabangorder');
        if($total==0)
        {
            echo "二次交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/11 \">";
            die;
        }**/
        if(count($rsdb)>0){
        }else{
            echo "二次交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/11 \">";
            die;
        }
        $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
        //根据店铺shopid获取相关授权信息
        $sql = "SELECT * FROM d_shop WHERE id = '{$orderID['shopid']}' ";
        $rs_row = $this->db->query($sql)->row_array();
        //店铺判断
        if($rs_row['name']=="ebay-LC"){
            $rs_row['name']="lovelycostume";
        }
        if($rs_row['name']=="ebay-LP"){
            $rs_row['name']="lovelyplaza";
        }
        if($rs_row['name']=="ebay-CC"){
            $rs_row['name']="coscart";
        }
        if($rs_row['name']=="Cosstyle2014"){
            $rs_row['name']="cosplaystyle2014";
        }
        if($rs_row['name']=="ebay-greatitemzone"){
            $rs_row['name']="greatitemzone";
        }
        if($rs_row['name']=="ebay-holydad"){
            $rs_row['name']="holydad";
        }
        if($rs_row['name']=="ebay-skyshow"){
            $rs_row['name']="skyshow";
        }
        if($rs_row['name']=="ebay-cossky"){
            $rs_row['name']="cossky";
        }
        if($rs_row['name']=="ebay-newlywonder"){
            $rs_row['name']="newlywonder";
        }
        //本地执行相关操作
        if(!empty($rs_row['amazonkey'])){
            $arr_auth = (array) json_decode($rs_row['amazonkey']);
        }else{
            echo "未正常获得到cnpost授权相关信息，请检查是否存在！";
            exit;
        }
        //判断是否远程代理访问
        /**  暂时仅针对本地
        if(isset($rs_row['agent_visit'])&&$rs_row['agent_visit']==1){
            $this->remoteDB = $this->load->database('amazondata',TRUE);
            $sql_remote = "SELECT * FROM db_ebay_cnpost WHERE orderID = '{$rsdb['orderID']}' ";
            $rs_remote  = $this->remoteDB->query($sql_remote)->row_array();
            $rsdb['shopid'] = $rs_row['id'];
            if(!$rs_remote){
                $this->remoteDB->insert('db_ebay_cnpost',$rsdb);
            }else{
                $this->remoteDB->update('db_ebay_cnpost',$rsdb,'id='.$rs_remote['id']);
            }
            $this->db->update('db_mabangorder',array('isexe'=>2,'exememo'=>'请耐心等待远程主机交运')," orderID='".$rsdb['orderID']."'");
            //echo "远程主机会交运该订单!";exit;
            $str = "远程主机会交运该订单!";
            return array('str'=>$str);  //交运下一条数据
        }**/
        //soap请求
        //组 Application Key 由三个 ID 组成， DevID, AppID, CertID，分别对应于 eBay 物流平台的请求中的
        //APIDevUserID，AppID， CertID。具体请参考第四部分接口说明。

        //new add 2017/7/26 确认提交到物流商系统中
        //发送请求  数组请求样式
        $url = "https://api.apacshipping.ebay.com.hk/aspapi/v4/ApacShippingService?wsdl"; //正式地址
        $client = new SoapClient($url);
        $arr_check['AppID']=$arr_auth['ebayappid'];
        $arr_check['APIDevUserID']=$arr_auth['ebaydevid'];
        $arr_check['AppCert']=$arr_auth['ebaycertid'];
        $arr_check['Version']="4.0.0";
        $arr_check['APISellerUserID'] = $rs_row['name'];
        $arr_check['APISellerUserToken'] = $arr_auth['ebayusertoken'];
        $arr_check['Carrier'] = "CNPOST"; //可用值：CNPOST UBI  DHL eCommerce
        //$arr_check['Service'] = "EPACK"; //可选
        $arr_check['MessageID'] = ""; //可选

        $arr_check['TrackCode'] = $rsdb['mailNo']; //Required
        $arr_check['PickUpRequestDateTime'] = ""; //可选
        //print_r($arr_check);exit;
        $p_data = array("ConfirmAPACShippingPackageRequest"=>$arr_check);
        $rs = (array) $client->ConfirmAPACShippingPackage($p_data);
        //new add end 7/26
        //返回值处理  交运单号 应该判断[Ack] => Failure 是否成功或失败
        if(isset($rs['ConfirmAPACShippingPackageResult']->Ack)&&$rs['ConfirmAPACShippingPackageResult']->Ack=="Success"){

            $arr_post_data['exememo'] = '交运成功';
            $arr_post_data["isexe"] = 1;
            //更新日志记录
            $imgdata = "";
            $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
            $imgdata["updatetime"] = date("Y-m-d H:i:s");
            $imgdata["createUid"] = $_COOKIE['userid'];
            $imgdata["types"] = 3;
            $imgdata["content"] = 'CNPOST二次交运成功,交易ID='.$orderID['tradeid'].",运单号：".$orderID["shipping_number"];
            $imgdata["createUser"] =$_COOKIE['username'];
            $this->db->insert('db_goods_log', $imgdata);

        }else{
            //判断交运失败的时候，是否存在运单号以及相关的pdf文档
            //$code = isset($rs['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Code)?$rs['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Code:"";
            $reasonMessage = isset($rs['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Message)?$rs['ConfirmAPACShippingPackageResult']->NotificationList->Notification->Message:""; //获取返回的错误信息
            //更新马帮表
            $exememo = '交运失败';
            $arr_post_data["isexe"] = 3;
            $exememo.='<br>'.$reasonMessage;
            $arr_post_data['exememo'] = $exememo;

        }
        $arr_post_data["mailinstime"] =time();
        $this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
        $str = $rsdb["orderID"].$arr_post_data['exememo'];
        return array('str'=>$str);
    }
    //全部放在本地了，无远程代码了，该代码不会执行
    //cnpost remote交运获取数据，更新到正式db_order_list db_mabangorder相关表
    public function remotecnpostexpress(){
        $this->remoteDB = $this->load->database('amazondata',TRUE);
        //所有交运成功
        $sql_remote = "SELECT * FROM db_ebay_cnpost WHERE (isexe = 1 or isexe = 2) AND isupload = 0 ";
        $rs_remote  = $this->remoteDB->query($sql_remote)->result_array();
        if(count($rs_remote)>0){
            foreach($rs_remote as $k=>$v){
                if($v['isexe']==1){
                    //更新db_order_list
                    $update_order['shipping_number'] = $v['mailNo'];
                    $update_order['shipping_name'] = "E邮宝";
                    $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='E邮宝'");
                    $update_order["shipping_id"] = $shipping["id"];
                    $this->db->update('db_order_list', $update_order, 'order_sn=' .$v["orderID"]);
                    //更新db_mabangorder
                    $arr_mabangorder['mailinstime'] = $v['mailinstime'];
                    $arr_mabangorder['exememo'] = $v['exememo'];
                    $arr_mabangorder['isexe'] = 1;
                    //$arr_mabangorder['printUrl'] = $v['printUrl'];
                    $arr_mabangorder['mailNo'] = $v['mailNo'];
                    //图片地址格式转换
                    $pic_url = "http://".$v['printUrl'];
                    $label_pdf_content = file_get_contents($pic_url); //pdf格式文档二进制流
                    //print_r($label_pdf_content);exit;
                    $dir = dirname(__FILE__) . "/../../uploads/cnpostexpress/".date("Ymd");
                    !is_dir($dir) && @mkdir($dir, 0755, true);
                    $Path_mailNo = $dir. "/".$v['mailNo']."_mailno.pdf";
                    //对获取的pdf流进行处理 标签
                    //$content=file_get_contents($label_content); //返回的就是pdf流
                    if(file_put_contents($Path_mailNo, $label_pdf_content)>0){
                        $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                        $arr_mabangorder["printUrl"] = $pathst;  //pdf格式文件地址
                        //实现pdf转换为png图片格式 放到线上做测试
                        $rsdbts = $this->pdf2png($Path_mailNo,"cnpostexpress"); //转为对应目录下存储
                        //可能不止一张图片
                        if(!empty($rsdbts[0])){
                            $image_urls=implode(",",$rsdbts);
                        }else{
                            $image_urls = $rsdbts[0];
                        }
                        $arr_mabangorder["print_img"] = $image_urls;
                    }
                    $this->db->update('db_mabangorder',$arr_mabangorder,'orderID='.$v["orderID"]);
                    //更新 远程 db_ebay_cnpost表 说明已经更新到66上了
                    $this->remoteDB->update('db_ebay_cnpost',array('isupload'=>1),'orderID='.$v['orderID']);
                }else{
                    $arr_mabangorder['mailinstime'] = $v['mailinstime'];
                    $arr_mabangorder['exememo'] = $v['exememo'];
                    $arr_mabangorder['isexe'] = $v['isexe'];
                    $this->db->update('db_mabangorder',$arr_mabangorder,'orderID='.$v["orderID"]);
                }

            }

        }

    }
    /********************************************
     * E邮宝交运
     **string
     ***********************************************/
	function getemsexpressPro()
	{
		 $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType = 8 ");
		 if(!$rsdb)
		 {
			echo "交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"2; url=/deliverorder/emsexpress/8 \">";
            die;
		 }

	   if($rsdb['logistics_account']=="苏州E邮宝"){
			if($this->config->item("emsexpressset")){
				$ems = stripslashes($this->config->item("emsexpressset"));
				$arr_ems = unserialize($ems);
				//暂时先测试  云途交运相关参数
				$url = $arr_ems['e_url'];
				$version = $arr_ems['e_version'];
				$apiToken = $arr_ems['e_token'];
				$mail_method = "苏州E邮宝";
                $mail_suzhou = 1;
			}else{
				echo "未正常获得到E邮宝接口，请在订单相关设置中检查是否正确！";
				exit;
			}
		}else{//上海E邮宝 默认方式
			if($this->config->item("eofflineexpressset")){
				$ems = stripslashes($this->config->item("eofflineexpressset"));
				$arr_ems = unserialize($ems);
				//暂时先测试  云途交运相关参数
				$url = $arr_ems['eoffline_url'];
				$version = $arr_ems['eoffline_version'];
				$apiToken = $arr_ems['eoffline_token'];
				$mail_method = "E邮包线下上海";
                $mail_suzhou = 0;
			}else{
				echo "未正常获得到E邮宝接口，请在订单相关设置中检查是否正确！";
				exit;
			}
		}

		 $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
		 $goodslist = $this->fun->getdatabaseslist("db_order_sell "," AND order_id='".$orderID["order_id"]."'");
		
		
        //手机必须为10位纯数字（如果填写的话）
        $mobile = str_replace("-","",$rsdb['customertel1']);
        $tel = str_replace("-","",$rsdb['customertel2']);
        $mobile = str_replace(" ","",$mobile);
        $tel = str_replace(" ","",$tel);
        if(strlen($mobile)){
            $mobile = substr($mobile,-10);
        }
        if(strlen($tel)){
            $tel = substr($tel,-10);
        }
        if(!$mobile){
            $mobile = $tel;
        }
        if(!$tel){
            $tel = $mobile;
        }
        //$rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
        $rsdb['customerzipcode'] = trim($rsdb['customerzipcode']);
        if(strlen($rsdb['customerzipcode'])>5){
            $rsdb["customerzipcode"] = substr($rsdb["customerzipcode"],0,10);
        }
        $rsdb["customeraddress"] = str_replace("&"," ",$rsdb["customeraddress"]);
        $rsdb["customeraddress"] = str_replace('\'',"'",$rsdb["customeraddress"]);
        $receiver = str_replace("&"," ",$orderID['consignee']);
        $receiver = str_replace("\\"," ",$receiver);
        $receiver = str_replace("-"," ",$receiver);
        $receiver = str_replace('\'',"'",$receiver);
        //订单id长度限制，最低四位
        $order_id = $orderID['order_id'];
        if(strlen($orderID['order_id'])<4){
            $order_id = str_pad($orderID['order_id'],4,"0",STR_PAD_LEFT);
        }
        $date = date("Y-m-d")."T".date("H:i:s");  //暂时测试
        if($rsdb['deliver']=="E包裹"){
            $perationtype = 1;
        }elseif($rsdb['deliver']=="E特快"){
            $perationtype = 2;
        }else{
            $perationtype = 0;
        }
        $producttype = 0;
        //如果选择E包裹，必填2
        if($perationtype==1){
            $producttype = 2;
        }

        //备注 country 等参数需要从他们的api查询出来，然后进行显示
		$xml_body="";
        $xml_body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        $xml_body.="<orders xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
        $xml_body.= "<order>";
        $xml_body.= "<orderid>{$order_id}</orderid><ordernum>{$orderID['order_sn']}</ordernum><operationtype>{$perationtype}</operationtype><producttype>{$producttype}</producttype>";
        $xml_body.= " <customercode>{$receiver}</customercode><vipcode></vipcode><clcttype>1</clcttype><pod>false</pod><untread>Returned</untread>";
        $xml_body.="<volweight>1</volweight><startdate>$date</startdate><enddate>$date</enddate><printcode>01</printcode>";
            if($rsdb['logistics_account']=="苏州E邮宝"){
                $xml_body.="<sender>";
                $xml_body.="<name>{$arr_ems['e_username']}</name><postcode>{$arr_ems['e_postcode']}</postcode><phone>{$arr_ems['e_mobile']}</phone><mobile>{$arr_ems['e_phone']}</mobile><country>{$arr_ems['e_countrycode']}</country><province>{$arr_ems['e_province']}</province>";
                $xml_body.="<city>{$arr_ems['e_city']}</city><county>{$arr_ems['e_area']}</county><company>{$arr_ems['e_company']}</company><street>{$arr_ems['e_address']}</street><email>{$arr_ems['e_email']}</email>";
                $xml_body.="</sender>";
            }else{
                $xml_body.="<sender>";
                $xml_body.="<name>{$arr_ems['eoffline_username']}</name><postcode>{$arr_ems['eoffline_postcode']}</postcode><phone>{$arr_ems['eoffline_phone']}</phone><mobile>{$arr_ems['eoffline_mobile']}</mobile><country>{$arr_ems['eoffline_countrycode']}</country><province>{$arr_ems['eoffline_province']}</province>";
                $xml_body.="<city>{$arr_ems['eoffline_city']}</city><county>{$arr_ems['eoffline_area']}</county><company>{$arr_ems['eoffline_company']}</company><street>{$arr_ems['eoffline_address']}</street><email>{$arr_ems['eoffline_email']}</email>";
                $xml_body.="</sender>";
            }
        if(!empty($rsdb['customerqq'])){
            $country_code = $rsdb['customerqq'];
        }else{
            $country_code = $orderID['country_code'];
        }
        //丹麦 西班牙

        if($rsdb["customerqq"]=="DK" || $rsdb["customerqq"]=="ES" || $rsdb["customerqq"]=="SE"){
            if(!$rsdb["customerprovince"]){
                $rsdb["customerprovince"] = $rsdb['customercity']; // 丹麦 西班牙 省份为空 ，默认同其城市
            }

        }

        $xml_body.="<receiver>";
        $xml_body.="<name>{$receiver}</name><postcode>{$rsdb["customerzipcode"]}</postcode><phone>{$tel}</phone><mobile>{$mobile}</mobile><country>{$country_code}</country><province>{$rsdb["customerprovince"]}</province>";
        $xml_body.="<city>{$rsdb['customercity']}</city><county>{$arr_ems['e_area']}</county><street>{$rsdb["customeraddress"]}</street>";
        $xml_body.="</receiver>";
        $xml_body.="<collect>";
            if($rsdb['logistics_account']=="苏州E邮宝"){
                $xml_body.="<name>{$arr_ems['e_username']}</name><postcode>{$arr_ems['e_postcode']}</postcode><phone>{$arr_ems['e_mobile']}</phone><mobile>{$arr_ems['e_phone']}</mobile><country>{$arr_ems['e_countrycode']}</country><province>{$arr_ems['e_province']}</province>";
                $xml_body.="<city>{$arr_ems['e_city']}</city><county></county><street>{$arr_ems['e_address']}</street><email>{$arr_ems['e_email']}</email>";
            }else{
                $xml_body.="<name>{$arr_ems['eoffline_username']}</name><postcode>{$arr_ems['eoffline_postcode']}</postcode><phone>{$arr_ems['eoffline_phone']}</phone><mobile>{$arr_ems['eoffline_mobile']}</mobile><country>{$arr_ems['eoffline_countrycode']}</country><province>{$arr_ems['eoffline_province']}</province>";
                $xml_body.="<city>{$arr_ems['eoffline_city']}</city><county>{$arr_ems['eoffline_area']}</county><street>{$arr_ems['eoffline_address']}</street><email>{$arr_ems['eoffline_email']}</email>";
            }
        $xml_body.="</collect>";
        $xml_body.="<items>";
        $number = 0;
        foreach($goodslist as $key=>$rs){
            $number = $number+$rs['goods_number'];
        }
        //如果 美国数量 大于等于五个 则另外一套算法
        if($number>=5&&$rsdb["customerqq"]=="US") {
            $unit_price = round(50 / $number, 2);
            $unit_weight = round(1.9 / $number, 2);
            foreach($goodslist as $key=>$rs)
            {
                $goods_data = $this->db->get_one("SELECT * FROM db_goods WHERE goods_id ='".$rs["goods_id"]."'");
                //$goods_data = $this->db->get_one("SELECT * FROM db_order_sell WHERE order_id = '{$orderID['order_id']}' AND  goods_id ='".$rs["goods_id"]."'");
               // $rs["goods_weight"] = $goods_data['g_weight']*$rs['goods_number'];
                $rs["goods_weight"] = $unit_weight*$rs['goods_number'];
                if($rs["goods_weight"]==0)
                {
                    $rs["goods_weight"] = 0.4;//单位kg
                }
               // $weightst = $rs["goods_weight"]/1000; //重量 单位kg
                $weightst = $rs["goods_weight"]; //重量 单位kg

                $xml_body.="<item>";
                $xml_body.="<cnname>周边小商品 2015</cnname><enname>costume accessories</enname><count>{$rs["goods_number"]}</count>";
                $xml_body.="<unit>件</unit><weight>{$weightst}</weight><delcarevalue>{$unit_price}</delcarevalue><origin>CN</origin>".
                    "<description></description><taxationid></taxationid><sellurl></sellurl>";
                $xml_body.="</item>";

            }



        }else{
            //默认计算方法
            foreach($goodslist as $key=>$rs)
            {
                $goods_data = $this->db->get_one("SELECT * FROM db_goods WHERE goods_id ='".$rs["goods_id"]."'");
                //$goods_data = $this->db->get_one("SELECT * FROM db_order_sell WHERE order_id = '{$orderID['order_id']}' AND  goods_id ='".$rs["goods_id"]."'");
                $rs["goods_weight"] = $goods_data['g_weight']*$rs['goods_number'];

                if($rs["goods_weight"]==0)
                {
                    $rs["goods_weight"] = 400;//单位g
                }
                $weightst = $rs["goods_weight"]/1000; //重量 单位kg

                $xml_body.="<item>";
                $xml_body.="<cnname>周边小商品 2015</cnname><enname>costume accessories</enname><count>{$rs["goods_number"]}</count>";
                $xml_body.="<unit>件</unit><weight>{$weightst}</weight><delcarevalue>22</delcarevalue><origin>CN</origin>".
                    "<description></description><taxationid></taxationid><sellurl></sellurl>";
                $xml_body.="</item>";

            }


        }
        $xml_body.="</items>";
        $xml_body.="</order>";
        $xml_body.="</orders>";

        //测试
        //$arr_order_xml= "";
        //$arr_order_xml['orders'] = $xml_body;
        //$arr_order_xml['addTime'] = date("Y-m-d H:i:s");
        //$this->db->insert('tmp_upload_order',$arr_order_xml);
        //$xml_insert_id = $this->db->insert_id();
       
	    $headers = array("Authenticate:{$apiToken}","Version: {$version}");
        $req_url = $url; //申请运单号请求路径
	     //获取请求的数据结果
        $xml_body_express = $this->sendCurlPostRequest($req_url,$xml_body,$headers);
        $xml_body_express = simplexml_load_string($xml_body_express,NULL,LIBXML_NOCDATA);
        $arr_body_express =json_decode(json_encode($xml_body_express),true);

        //返回值处理  交运单号
        if(isset($arr_body_express['mailnum'])&&$arr_body_express['mailnum']){
         
			$arr_post_data="";
            $arr_post_data['exememo'] = '交运成功';
            $arr_post_data['mailNo'] = $arr_body_express['mailnum']; //运单号
            $arr_post_data["isexe"] = 1;
            $arr_post_data["originCode"] = 0;
            $arr_post_data["destCode"] = 0;
            //标签地址
            $md5auth = md5($apiToken.$arr_post_data['mailNo']);
            $label_url = "http://labels.ems.com.cn/partner/api/public/p/static/label/download/{$md5auth}/{$arr_post_data['mailNo']}.pdf";
            $arr_post_data["printUrl"] = $label_url;

            //判断是否为有效的交运，若交运有效存在pdf文档，则交运成功，否则交运失败
            /**
            $handle = curl_init($label_url);
            curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);//设置超时时间
            curl_exec($handle);
            //检查是否404（网页找不到）
            $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            if($httpCode==404) {
                return $rsdb["orderID"]."交运失败，没有返回有效的pdf文档";
            }
            curl_close($handle);
            **/
            //判断是否是苏州E邮宝进行交运的，若是则保存相关jpg文件
            /**
            if($mail_suzhou==1){
                $dir = dirname(__FILE__) . "/../../uploads/emsexpress/".date("Ymd");
                !is_dir($dir) && @mkdir($dir, 0755, true);
                $Path_mailNo = $dir. "/".$arr_post_data['mailNo']."_mailno.pdf";
                //对获取的pdf流进行处理 标签
                $content=file_get_contents($label_url);
                if(file_put_contents($Path_mailNo, $content)>0){
                    $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                     $rsdbts = $this->pdf2png($Path_mailNo,"emsexpress"); //转为对应目录下存储
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    //可能不止一张图片
                     if(!empty($rsdbts[0])){
                            $image_urls=implode(",",$rsdbts);
                            $arr_post_data["print_img"] = $image_urls;
                     }else{
                            $arr_post_data["print_img"] = $rsdbts[0];
                            $image_urls = $rsdbts[0];
                     }
                }
            }**/


            /**注销该段代码，目前仅保存，pdf的相关地址 远程服务器
            $dir = dirname(__FILE__) . "/../../uploads/emsexpress/".date("Ymd");
            !is_dir($dir) && @mkdir($dir, 0755, true);
            $Path_mailNo = $dir. "/".$arr_post_data['mailNo']."_mailno.pdf";
            //对获取的pdf流进行处理 标签
            $content=file_get_contents($label_url);
            if(file_put_contents($Path_mailNo, $content)>0){
                $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                //实现pdf转换为png图片格式 放到线上做测试
               // $rsdbts = $this->pdf2png($Path_mailNo,"emsexpress"); //转为对应目录下存储
                //$arr_post_data["print_img"] = $rsdbts[0];
                //可能不止一张图片
               // if(!empty($rsdbts[0])){
                 //   $image_urls=implode(",",$rsdbts);
                    // $arr_post_data["print_img"] = $image_urls;
               // }else{
                    //$arr_post_data["print_img"] = $rsdbts[0];
               //     $image_urls = $rsdbts[0];
               // }
            }**/


            //$arr_post_data["print_img"] = $image_urls;

            //$arr_post_data["printUrl_declare"] = $label_url;
            //var_dump($arr_body_express);exit;
            $update_order = "";
            $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
            $update_order["shipping_time"] = time();				//交运时间
            if($mail_suzhou==1){
                $update_order["shipping_name"] = "苏州 E邮宝线下";
                //$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
                $update_order["shipping_id"] = 47; //shipping_id号
            }else{
                $update_order["shipping_name"] = "E邮包线下上海";
                $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
                $update_order["shipping_id"] = $shipping["id"];
            }
            $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
            //更新日志记录
				$imgdata="";
                $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid'].",运单号为".$arr_post_data['mailNo'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                //放到里面执行  8/22
            $arr_post_data["mailinstime"] =time();
            //$this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
            $this->db->update('db_mabangorder',$arr_post_data, 'id=' .$rsdb["id"]);
            $str = $rsdb["orderID"].$arr_post_data['exememo'];
			$xml_body="";
            return array('str'=>$str);


        }else{
            $reasonMessage = $arr_body_express['description']; //获取返回的错误信息
            //更新马帮表
            $exememo = '交运失败';
			$arr_post_data="";
            $arr_post_data["isexe"] = 2;
            $exememo.='<br>'.$reasonMessage;
            $arr_post_data['exememo'] = $exememo;
           //放到里面执行 8/22
            $arr_post_data["mailinstime"] =time();
            //$this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
            $this->db->update('db_mabangorder',$arr_post_data, 'id=' .$rsdb["id"]);
            $str = $rsdb["orderID"].$arr_post_data['exememo'];
			$xml_body="";
            return array('str'=>$str);
        }

	}
    public function getemsexpresstest()
    {
        $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType = 8 ");
            if($rsdb['logistics_account']=="苏州E邮宝"){
                if($this->config->item("emsexpressset")){
                    $ems = stripslashes($this->config->item("emsexpressset"));
                    $arr_ems = unserialize($ems);
                    //暂时先测试  云途交运相关参数
                    $url = $arr_ems['e_url'];
                    $version = $arr_ems['e_version'];
                    $apiToken = $arr_ems['e_token'];
                    $mail_method = "苏州E邮宝";
                }else{
                    echo "未正常获得到E邮宝接口，请在订单相关设置中检查是否正确！";
                    exit;
                }
            }else{//上海E邮宝 默认方式
                if($this->config->item("eofflineexpressset")){
                    $ems = stripslashes($this->config->item("eofflineexpressset"));
                    $arr_ems = unserialize($ems);
                    //暂时先测试  云途交运相关参数
                    $url = $arr_ems['eoffline_url'];
                    $version = $arr_ems['eoffline_version'];
                    $apiToken = $arr_ems['eoffline_token'];
                    $mail_method = "E邮包线下上海";
                }else{
                    echo "未正常获得到E邮宝接口，请在订单相关设置中检查是否正确！";
                    exit;
                }
            }
        //根据令牌交运
        if(count($rsdb)>0){
        }else{
            echo "交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"2; url=/deliverorder/emsexpress/8 \">";
            die;
        }
        /**
        $where  = "isexe = 0 AND orderType =8";
        $this->db->where($where);
        $total = $this->db->count_all_results('db_mabangorder');
        if($total==0)
        {
            echo "交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"2; url=/deliverorder/emsexpress/8 \">";
            die;
        }**/
        $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
   
        $goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B on A.goods_id = B.goods_id"," AND A.order_id='".$orderID["order_id"]."'"." GROUP BY A.rec_id ");

        //请求相关参数 含方法 数据等 post方式
        $headers = array("Authenticate:{$apiToken}","Version: {$version}");
        $req_url = $url; //申请运单号请求路径
        //手机必须为10位纯数字（如果填写的话）
        $mobile = str_replace("-","",$rsdb['customertel1']);
        $tel = str_replace("-","",$rsdb['customertel2']);
        $mobile = str_replace(" ","",$mobile);
        $tel = str_replace(" ","",$tel);
        if(strlen($mobile)){
            $mobile = substr($mobile,-10);
        }
        if(strlen($tel)){
            $tel = substr($tel,-10);
        }
        if(!$mobile){
            $mobile = $tel;
        }
        if(!$tel){
            $tel = $mobile;
        }
        //$rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
        $rsdb['customerzipcode'] = trim($rsdb['customerzipcode']);
        if(strlen($rsdb['customerzipcode'])>5){
            $rsdb["customerzipcode"] = substr($rsdb["customerzipcode"],0,10);
        }
        $rsdb["customeraddress"] = str_replace("&"," ",$rsdb["customeraddress"]);
        $rsdb["customeraddress"] = str_replace('\'',"'",$rsdb["customeraddress"]);
        $receiver = str_replace("&"," ",$orderID['consignee']);
        $receiver = str_replace("\\"," ",$receiver);
        $receiver = str_replace("-"," ",$receiver);
        $receiver = str_replace('\'',"'",$receiver);
        //订单id长度限制，最低四位
        $order_id = $orderID['order_id'];
        if(strlen($orderID['order_id'])<4){
            $order_id = str_pad($orderID['order_id'],4,"0",STR_PAD_LEFT);
        }
        $date = date("Y-m-d")."T".date("H:i:s");  //暂时测试
        if($rsdb['deliver']=="E包裹"){
            $perationtype = 1;
        }elseif($rsdb['deliver']=="E特快"){
            $perationtype = 2;
        }else{
            $perationtype = 0;
        }
        $producttype = 0;
        //如果选择E包裹，必填2
        if($perationtype==1){
            $producttype = 2;
        }

        //备注 country 等参数需要从他们的api查询出来，然后进行显示
        $xml_body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        $xml_body.="<orders xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
        $xml_body .= "<order>";
        $xml_body.= "<orderid>{$order_id}</orderid><ordernum>{$orderID['order_sn']}</ordernum><operationtype>{$perationtype}</operationtype><producttype>{$producttype}</producttype>";
        $xml_body.= " <customercode>{$receiver}</customercode><vipcode></vipcode><clcttype>1</clcttype><pod>false</pod><untread>Returned</untread>";
        $xml_body.="<volweight>1</volweight><startdate>$date</startdate><enddate>$date</enddate><printcode>01</printcode>";
            if($rsdb['logistics_account']=="苏州E邮宝"){
                $xml_body.="<sender>";
                $xml_body.="<name>{$arr_ems['e_username']}</name><postcode>{$arr_ems['e_postcode']}</postcode><phone>{$arr_ems['e_phone']}</phone><mobile>{$arr_ems['e_mobile']}</mobile><country>{$arr_ems['e_countrycode']}</country><province>{$arr_ems['e_province']}</province>";
                $xml_body.="<city>{$arr_ems['e_city']}</city><county></county><company>{$arr_ems['e_company']}</company><street>{$arr_ems['e_address']}</street><email>{$arr_ems['e_email']}</email>";
                $xml_body.="</sender>";
            }else{
                $xml_body.="<sender>";
                $xml_body.="<name>{$arr_ems['eoffline_username']}</name><postcode>{$arr_ems['eoffline_postcode']}</postcode><phone>{$arr_ems['eoffline_phone']}</phone><mobile>{$arr_ems['eoffline_mobile']}</mobile><country>{$arr_ems['eoffline_countrycode']}</country><province>{$arr_ems['eoffline_province']}</province>";
                $xml_body.="<city>{$arr_ems['eoffline_city']}</city><county>{$arr_ems['eoffline_area']}</county><company>{$arr_ems['eoffline_company']}</company><street>{$arr_ems['eoffline_address']}</street><email>{$arr_ems['eoffline_email']}</email>";
                $xml_body.="</sender>";
            }
        if(!empty($rsdb['customerqq'])){
            $country_code = $rsdb['customerqq'];
        }else{
            $country_code = $orderID['country_code'];
        }

        $xml_body.="<receiver>";
        $xml_body.="<name>{$receiver}</name><postcode>{$rsdb["customerzipcode"]}</postcode><phone>{$tel}</phone><mobile>{$mobile}</mobile><country>{$country_code}</country><province>{$rsdb["customerprovince"]}</province>";
        $xml_body.="<city>{$rsdb['customercity']}</city><county></county><street>{$rsdb["customeraddress"]}</street>";
        $xml_body.="</receiver>";
        $xml_body.="<collect>";
            if($rsdb['logistics_account']=="苏州E邮宝"){
                $xml_body.="<name>{$arr_ems['e_username']}</name><postcode>{$arr_ems['e_postcode']}</postcode><phone>{$arr_ems['e_phone']}</phone><mobile>{$arr_ems['e_mobile']}</mobile><country>{$arr_ems['e_countrycode']}</country><province>{$arr_ems['e_province']}</province>";
                $xml_body.="<city>{$arr_ems['e_city']}</city><county></county><street>{$arr_ems['e_address']}</street><email>{$arr_ems['e_email']}</email>";
            }else{
                $xml_body.="<name>{$arr_ems['eoffline_username']}</name><postcode>{$arr_ems['eoffline_postcode']}</postcode><phone>{$arr_ems['eoffline_phone']}</phone><mobile>{$arr_ems['eoffline_mobile']}</mobile><country>{$arr_ems['eoffline_countrycode']}</country><province>{$arr_ems['eoffline_province']}</province>";
                $xml_body.="<city>{$arr_ems['eoffline_city']}</city><county>{$arr_ems['eoffline_area']}</county><street>{$arr_ems['eoffline_address']}</street><email>{$arr_ems['eoffline_email']}</email>";
            }
        $xml_body.="</collect>";
        $xml_body.="<items>";
        $number = 0;
        foreach($goodslist as $key=>$rs)
        {
            if( $rs["goods_weight"]==0)
            {
                //$rs["goods_weight"] = 0.4;//单位kg
                //更改为克，因为单位都是克，方便下文计算
                $rs["goods_weight"] = 400;//单位g
            }
            //$weightst = ($rs["goods_number"] * $rs["goods_weight"])/1000; //重量 单位kg
            $weightst = $rs["goods_weight"]/1000; //重量 单位kg
            //$weight= $weight+$weightst;
            //$weight=ceil($weight);
            //重量
            //$weight=0.4;
            $number = $number+$rs["goods_number"];
            $xml_body.="<item>";
            $xml_body.="<cnname>周边小商品 2015</cnname><enname>costume accessories</enname><count>{$rs["goods_number"]}</count>";
            $xml_body.="<unit>件</unit><weight>{$weightst}</weight><delcarevalue>22</delcarevalue><origin>CN</origin>".
                        "<description></description><taxationid></taxationid><sellurl></sellurl>";
            $xml_body.="</item>";
        }
        $xml_body.="</items>";
        $xml_body.="</order>";
        $xml_body.="</orders>";

        //测试
        /**
        $arr_order_xml['orders'] = $xml_body;
        $arr_order_xml['addTime'] = date("Y-m-d H:i:s");
        $this->db->insert('tmp_upload_order',$arr_order_xml);
        $xml_insert_id = $this->db->insert_id();
        **/
		//echo $xml_body;exit;
        //获取请求的数据结果
        $xml_body_express = $this->sendCurlPostRequest($req_url,$xml_body,$headers);
        $xml_body_express = simplexml_load_string($xml_body_express,NULL,LIBXML_NOCDATA);
        $arr_body_express =json_decode(json_encode($xml_body_express),true);

        //返回值处理  交运单号
        if(isset($arr_body_express['mailnum'])&&$arr_body_express['mailnum']){
            //测试
            /**
            $tmp_data =  $arr_body_express['mailnum']."-".$orderID['order_sn'];
            $this->db->update('tmp_upload_order',array('goods'=>$tmp_data),'id = '.$xml_insert_id);
             **/
			$arr_post_data="";
            $arr_post_data['exememo'] = '交运成功';
            $arr_post_data['mailNo'] = $arr_body_express['mailnum']; //运单号
            $arr_post_data["isexe"] = 1;
            $arr_post_data["originCode"] = 0;
            $arr_post_data["destCode"] = 0;
            //标签地址
            $md5auth = md5($apiToken.$arr_post_data['mailNo']);
            $label_url = "http://labels.ems.com.cn/partner/api/public/p/static/label/download/{$md5auth}/{$arr_post_data['mailNo']}.pdf";
            $dir = dirname(__FILE__) . "/../../uploads/emsexpress/".date("Ymd");
            !is_dir($dir) && @mkdir($dir, 0755, true);
            $Path_mailNo = $dir. "/".$arr_post_data['mailNo']."_mailno.pdf";
            //对获取的pdf流进行处理 标签
            $content=file_get_contents($label_url);
            if(file_put_contents($Path_mailNo, $content)>0){
                $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                //实现pdf转换为png图片格式 放到线上做测试
                $rsdbts = $this->pdf2png($Path_mailNo,"emsexpress"); //转为对应目录下存储
                //$arr_post_data["print_img"] = $rsdbts[0];
                //可能不止一张图片
                if(!empty($rsdbts[0])){
                    $image_urls=implode(",",$rsdbts);
                    // $arr_post_data["print_img"] = $image_urls;
                }else{
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    $image_urls = $rsdbts[0];
                }
            }
            $arr_post_data["print_img"] = $image_urls;

            //$arr_post_data["printUrl_declare"] = $label_url;
            //var_dump($arr_body_express);exit;
            $update_order = "";
            $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
            $update_order["shipping_time"] = time();				//交运时间
            //$update_order["shipping_name"] = "UPS";
            /**
            if($rsdb['deliver']=="E邮宝"){
                $update_order["shipping_name"] = "E邮包线下上海";
            }else{
                $update_order["shipping_name"] = $rsdb['deliver'];
            }**/
            $update_order["shipping_name"] = "E邮包线下上海";
            $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
            $update_order["shipping_id"] = $shipping["id"];
            //$update_order["shipping_expectfee"] = ""; 需要通过计算
            $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
            //var_dump($arr_body_express);exit;
            //更新日志记录
                $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid'].",运单号为".$arr_post_data['mailNo'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                //放到里面执行  8/22
            $arr_post_data["mailinstime"] =time();
            //$this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
            $this->db->update('db_mabangorder',$arr_post_data, 'id=' .$rsdb["id"]);
            $str = $rsdb["orderID"].$arr_post_data['exememo'];
            return array('str'=>$str);


        }else{
            $reasonMessage = $arr_body_express['description']; //获取返回的错误信息
            //更新马帮表
            $exememo = '交运失败';
            $arr_post_data["isexe"] = 2;
            $exememo.='<br>'.$reasonMessage;
            $arr_post_data['exememo'] = $exememo;
            // echo $reasonMessage;exit;

            //放到里面执行 8/22
            $arr_post_data["mailinstime"] =time();
            //$this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
            $this->db->update('db_mabangorder',$arr_post_data, 'id=' .$rsdb["id"]);
            $str = $rsdb["orderID"].$arr_post_data['exememo'];
            return array('str'=>$str);
        }


    }
    /********************************************
     * 云途交运
     **string
     ***********************************************/
    public function getyuntuexpress()
    {
        if($this->config->item("yuntuexpressset")){
            $yuntu = stripslashes($this->config->item("yuntuexpressset"));
            $arr_yuntu = unserialize($yuntu);
        }else{
            echo "未正常获得到云途接口，请在订单相关设置中检查是否正确！";
            exit;
        }
        //暂时先测试  云途交运相关参数
        $url = $arr_yuntu['y_url'];
        $userid = $arr_yuntu['y_version']; //客户编号
        $apiSecret = $arr_yuntu['y_token']; //apisecret
        $token = $userid."&".$apiSecret;
        $apiToken = base64_encode($token);
            //根据令牌交运
            $where  = "isexe = 0 AND orderType =6";
            $this->db->where($where);
            $total = $this->db->count_all_results('db_mabangorder');
            if($total==0)
            {
                echo "交运完成！";
                echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/6 \">";
                die;
            }
            $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =6 ORDER BY id DESC");
            $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
            //$goodslist = $this->db->get_where('db_order_sell',"order_id ='".$orderID["order_id"]."'")->result_array();
            $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
            //$goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B on A.goods_id = B.goods_id"," AND A.order_id='".$orderID["order_id"]."'");
            $goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B on A.goods_id = B.goods_id left join db_goods C on A.goods_id = C.goods_id"," AND A.order_id='".$orderID["order_id"]."'"." GROUP BY A.rec_id ");
            //var_dump($goodslist);exit;
            //定义数组
            $arr_json_postdata = array(); //需要传递过去的json数据
            //请求相关参数 含方法 数据等 post方式
            $headers = array("Authorization:Basic {$apiToken}","Accept: text/json;","Content-Type: application/json");
            $req_url = $url.'WayBill/BatchAdd'; //申请运单号请求路径
            //测试 查询运输方式 //只使用四个专线，判断区别对待
            /**
            $r_url = $url."lms/Get?countryCode={$rsdb['customerqq']}";
            $rs_url = $this->sendCurlGetRequest($r_url,$headers);
            $arr_code = (array) json_decode($rs_url);
            if(isset($arr_code['Item'][1]->Code)){
                $deliver_code = $arr_code['Item'][1]->Code;  //根据国家代码查运输方式
            }else{
                $deliver_code = "";
            }**/
            $deliver_code = "";
            $rsdb['deliver'] = trim($rsdb['deliver']);
            if($rsdb['deliver']=="云途德国专线平邮"){
                $deliver_code = "DEZXA";
            }
            if($rsdb['deliver']=="云途中欧专线平邮"){
                $deliver_code = "EUDDPG";   //保留之前数据，这个暂时不用了
            }
            if($rsdb['deliver']=="云途中欧专线挂号"){
                $deliver_code = "EUDDP";
            }
            if($rsdb['deliver']=="中美专线(特惠)"){
                $deliver_code = "USZXR";
            }
            if($rsdb['deliver']=="云途德国专线挂号"){
                $deliver_code = "DEZXR";
            }
            if($rsdb['deliver']=="云途法国专线挂号"){
                $deliver_code = "FRZXR";
            }
            if($rsdb['deliver']=="云途英国专线标准"){
                $deliver_code = "GBZXR";
            }
            //echo $rs_url;exit;
            //手机必须为10位纯数字（如果填写的话）
            $mobile = str_replace("-","",$rsdb['customertel1']);
            $tel = str_replace("-","",$rsdb['customertel2']);
            if(strlen($mobile)){
                $mobile = substr($mobile,-10);
            }
            if(strlen($tel)){
                $tel = substr($tel,-10);
            }


            //$rsdb["customerzipcode"] = substr($rsdb["customerzipcode"],0,5);

            //英国 收件人邮编 必填项,2-4位数字或字母+空格+3位数字或字母(空格可不填)
            if($rsdb["customerqq"]=="GB" ||$rsdb["customerqq"]=="UK"){ //英国
                $rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
                $rsdb["customerzipcode"] = str_replace(" ","",$rsdb["customerzipcode"]);
            }else if($rsdb["customerqq"]=="DE" || $rsdb["customerqq"]=="FR"){
                $rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
                $rsdb["customerzipcode"] = substr($rsdb["customerzipcode"],0,5);
            }else if($rsdb["customerqq"]=="SE"){ //瑞典五位纯数字
                $rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
                $rsdb["customerzipcode"] = str_replace(" ","",$rsdb["customerzipcode"]);
            }else if($rsdb["customerqq"]=="GR" || $rsdb["customerqq"]=="CZ"){ //希腊 捷克
                $rsdb["customerzipcode"] = str_replace(" ","",$rsdb["customerzipcode"]);
                $rsdb["customerzipcode"] = substr(trim($rsdb["customerzipcode"]),0,3)." ".substr(trim($rsdb["customerzipcode"]),0,2);
            }
            else if($rsdb["customerqq"]=="NL"){ //希腊 捷克
                $rsdb["customerzipcode"] = str_replace(" ","",$rsdb["customerzipcode"]);
                $rsdb["customerzipcode"] = substr(trim($rsdb["customerzipcode"]),0,4)." ".substr(trim($rsdb["customerzipcode"]),4,2);
            }
            else{

            }
            $rsdb["customeraddress"] = str_replace(",",".",$rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("，",".",$rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("\n","",$rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("é","e",$rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("ü","u",$rsdb["customeraddress"]);
            $rsdb['customeraddress'] = str_replace("ß","B",$rsdb['customeraddress']);
            $rsdb['customeraddress'] = str_replace("ó","o",$rsdb['customeraddress']);
            $rsdb['customeraddress'] = str_replace("í","i",$rsdb['customeraddress']);
            $rsdb['customeraddress'] = str_replace("â","a",$rsdb['customeraddress']);
            $rsdb['customeraddress'] = str_replace("1ª","1",$rsdb['customeraddress']);

            $straddress = strlen(trim($rsdb["customeraddress"]));
            if($straddress<=35)
            {
                $address1 = trim($rsdb["customeraddress"]);
                $address2 = "";
                $address3 = "";
            }else{
                $address1 = substr($rsdb["customeraddress"],0,35);
                $address2 = substr($rsdb["customeraddress"],35,70);
                $address3 = substr($rsdb["customeraddress"],70,105);
            }
            //channel 中邮上海平邮小包   中邮上海挂号小包  两种为固定的
            $arr_order['WayBillNumber'] = "";
            $arr_order['TrackingNumber'] = "";
            $arr_order['OrderNumber'] = $orderID['order_sn'];
            //$arr_order['ShippingMethodCode'] = $rsdb['deliver'];
            $arr_order['ShippingMethodCode'] = $deliver_code; //测试
           // $arr_order['ShippingMethodCode'] = "CNDWR"; //测试
            $arr_order['Weight'] = 0.4;
            $arr_order['TotalFee'] = null;
            $arr_order['TotalQty'] = null;
            $arr_order['SettleWeight'] = null;
            $arr_order['PackageVolume'] = 1;
            $arr_order['PackageNumber'] = 1;  //必填  下文填写
            $arr_order['Length'] = 1;
            $arr_order['Height'] = 1;
            $arr_order['ShippingInfo']['ShippingTaxId'] = "";
            if($rsdb['customerqq']=="UK"){
                $rsdb['customerqq'] = "GB";
            }
            $arr_order['ShippingInfo']['CountryCode'] = $rsdb['customerqq'];   //必填

            //收件人
            $receiver = str_replace("ü","u",$orderID['consignee']);
            $receiver = str_replace("é","e",$receiver);
            //$receiver = explode(",",$receiver);
            $arr_order['ShippingInfo']['ShippingFirstName'] = $receiver; //必填
            $arr_order['ShippingInfo']['ShippingLastName'] = "";
            $arr_order['ShippingInfo']['ShippingAddress'] = $address1; //必填
            $arr_order['ShippingInfo']['ShippingAddress1'] = $address2;
            $arr_order['ShippingInfo']['ShippingAddress2'] = $address3;
            //城市过滤
            $rsdb['customercity'] = str_replace("é","e",$rsdb['customercity']);
            $rsdb['customercity'] = str_replace("í","i",$rsdb['customercity']);
            $rsdb['customercity'] = str_replace("i","i",$rsdb['customercity']);

            $arr_order['ShippingInfo']['ShippingCity'] = $rsdb['customercity']; //必填
            if(!$rsdb['customerprovince']){
                $arr_order['ShippingInfo']['ShippingState'] = $rsdb["customercity"];
            }else{
                $arr_order['ShippingInfo']['ShippingState'] = $rsdb["customerprovince"];
            }

            $arr_order['ShippingInfo']['ShippingZip'] = $rsdb["customerzipcode"];
            $tel_mobile = isset($tel)&&$tel?$tel:$mobile;
            $arr_order['ShippingInfo']['ShippingPhone'] = $tel_mobile;
            //发货 非必填
            $arr_order['SenderInfo']['CountryCode'] = $arr_yuntu['y_countrycode'];
            $arr_order['SenderInfo']['SenderFirstName'] = $arr_yuntu['y_xing'];
            $arr_order['SenderInfo']['SenderLastName'] = $arr_yuntu['y_name'];
            $arr_order['SenderInfo']['SenderCompany'] = $arr_yuntu['y_company'];
            $arr_order['SenderInfo']['SenderAddress'] = $arr_yuntu['y_address'];
            $arr_order['SenderInfo']['SenderCity'] = $arr_yuntu['y_city'];
            $arr_order['SenderInfo']['SenderState'] = $arr_yuntu['y_province'];
            $arr_order['SenderInfo']['SenderZip'] = $arr_yuntu['y_postcode'];
            $arr_order['SenderInfo']['SenderPhone'] = $arr_yuntu['y_mobile']?$arr_yuntu['y_mobile']:$arr_yuntu['y_phone'];
            //保险
            $arr_order['IsReturn'] = true;
            $arr_order['ApplicationType'] = 1; //申报类型,用于打印CN22，1-Gift,2-Sameple,3-Documents,4-Others,默认4-Other
            //$arr_order['EnableTariffPrepay'] = 1;
            $arr_order['InsuranceType'] = 0;
            $arr_order['InsureAmount'] = 0;
            $arr_order['SensitiveTypeID'] = ""; //包裹中特殊货品类型，可调用货品类型查询服务查询，可以不填写，表示普通货品
            //产品信息
            $number = 0;
            $sku_num = 0;
            foreach($goodslist as $key=>$rs)
            {
                if(!$rs['en_goods_name']){
                    $rs['en_goods_name'] = "costume accessory";
                }else{
                    $rs['en_goods_name'] = $this->strFilter($rs['en_goods_name']);
                    if(strlen($rs['en_goods_name'])>100){
                        $rs['en_goods_name'] = substr($rs['en_goods_name'],0,99);
                    }
                    $rs['en_goods_name'] = str_replace("ü","u",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("＇","'",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("ß","",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("‘","",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("ä","a",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("à","a",$rs['en_goods_name']);
                    $rs['en_goods_name'] = str_replace("i","i",$rs['en_goods_name']);

                }
                $arr_order['ApplicationInfos'][$key]['ApplicationName'] = $rs['en_goods_name']; //测试
                $arr_order['ApplicationInfos'][$key]['HSCode'] = "69251"; //欧洲专线必填
                $arr_order['ApplicationInfos'][$key]['Qty'] = $rs["goods_number"];
                $arr_order['ApplicationInfos'][$key]['UnitPrice'] = 6; //固定
                $arr_order['ApplicationInfos'][$key]['UnitWeight'] = 0.4; //固定
                $arr_order['ApplicationInfos'][$key]['PickingName'] = $rs['goods_name'];
                $arr_order['ApplicationInfos'][$key]['Remark'] = "";
                //$arr_order['ApplicationInfos'][$key]['ProductUrl'] = "";
                $arr_order['ApplicationInfos'][$key]['SKU'] = $rs['goods_sn'];
                $number = $number+$rs["goods_number"];
                $sku_num = $sku_num+1;
            }
            //如果商品数量超过十个的话，每一个申报1美金
            if($number>=4){
                $unit_price = round(19/$number,2);
                $unit_weight= round(1.9/$number,2);
                foreach($goodslist as $key=>$rs)
                {
                    if(!$rs['en_goods_name']){
                        $rs['en_goods_name'] = "costume accessory";
                    }else{
                        $rs['en_goods_name'] = $this->strFilter($rs['en_goods_name']);
                        if(strlen($rs['en_goods_name'])>100){
                            $rs['en_goods_name'] = substr($rs['en_goods_name'],0,99);
                        }
                        $rs['en_goods_name'] = trim($rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("ü","u",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("＇","'",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("ß","",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("‘","",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("ä","a",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("à","a",$rs['en_goods_name']);
                        $rs['en_goods_name'] = str_replace("i","i",$rs['en_goods_name']);
                    }
                    $arr_order['ApplicationInfos'][$key]['ApplicationName'] = $rs['en_goods_name']; //测试
                    $arr_order['ApplicationInfos'][$key]['HSCode'] = "69251"; //欧洲专线必填
                    $arr_order['ApplicationInfos'][$key]['Qty'] = $rs["goods_number"];
                    $arr_order['ApplicationInfos'][$key]['UnitPrice'] = $unit_price; //固定
                    $arr_order['ApplicationInfos'][$key]['UnitWeight'] = $unit_weight; //固定
                    $arr_order['ApplicationInfos'][$key]['PickingName'] = $rs['goods_name'];
                    $arr_order['ApplicationInfos'][$key]['Remark'] = "";
                    //$arr_order['ApplicationInfos'][$key]['ProductUrl'] = "";
                    $arr_order['ApplicationInfos'][$key]['SKU'] = $rs['goods_sn'];
                }
            }


            $arr_order['PackageNumber'] = $number;  //必填
            $arr_json_postdata[] = $arr_order;
            //print_r($arr_json_postdata);exit;
            $json_post = json_encode($arr_json_postdata);
             //echo $json_post;exit;
            //获取请求的数据结果
            $json_body_express = $this->sendCurlPostRequest($req_url,$json_post,$headers);
            $arr_body_express = (array) json_decode($json_body_express);
             //$arr_body_express['ResultCode']=="1001" 为提交的订单号已经存在，则更新订单号重新交运
            // $arr_body_express['Item'][0]->WayBillNumber 为运单号
            if(isset($arr_body_express['ResultCode'])&&$arr_body_express['ResultCode']=="1001"){
                $arr_order['OrderNumber'] = $orderID['order_sn']."-".rand(111111,999999);
                $a_json_postdata[] = $arr_order;
                $json_post = json_encode($a_json_postdata);
                $json_body_express = $this->sendCurlPostRequest($req_url,$json_post,$headers);
                $arr_body_express = (array) json_decode($json_body_express);
                if(isset($arr_body_express['ResultCode'])&&$arr_body_express['ResultCode']=="0000"){
                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $orderID['order_id'];	//订单ID db_order_list 就是tradeid
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 6;
                    $imgdata["content"] = '二次交运,交易ID='.$arr_order['OrderNumber'].",运单号=".$arr_body_express['Item'][0]->WayBillNumber;
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);
                }

            }
            //print_r($arr_body_express);exit;
            //返回值处理  交运单号
            if(isset($arr_body_express['ResultCode'])&&$arr_body_express['ResultCode']=="0000"){
                $arr_post_data['exememo'] = '交运成功';
                $arr_post_data['mailNo'] = $arr_body_express['Item'][0]->WayBillNumber; //运单号
                $arr_post_data["isexe"] = 1;
                $arr_post_data["originCode"] = 0;
                $arr_post_data["destCode"] = 0;
                //标签地址
                $label_return_url = "http://api.yunexpress.com/LMS.API.Lable/Api/PrintUrl"; //标签获取地址
                $label_req_data = json_encode(array($orderID['order_sn']));
                $label_return_rs = $this->sendCurlPostRequest($label_return_url,$label_req_data,$headers);
                $arr_label_return_rs = json_decode($label_return_rs);
                $label_url =$arr_label_return_rs->Item[0]->Url;
                $arr_post_data["printUrl"] = $label_url;  //pdf格式文件地址
                
                /**
                $dir = dirname(__FILE__) . "/../../"."uploads/yuntuexpress/".date("Ymd");
                !is_dir($dir) && @mkdir($dir, 0755, true);
                $Path_mailNo = $dir. "/".$arr_body_express['Item'][0]->WayBillNumber."-".time().".pdf";
                //对获取的pdf流进行处理 标签

                $content=file_get_contents($label_url);
                if(file_put_contents($Path_mailNo, $content)>0){
                    $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                        $rsdbts = $this->pdf2png($Path_mailNo, "yuntuexpress");
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                    $rsdbts = $this->pdf2png($Path_mailNo, "yuntuexpress");
                    $arr_post_data["printUrl"] = $label_url;  //pdf格式文件地址
					$arr_post_data["print_img"] = $pathst;
                       // $rsdbts = $this->pdf2png($Path_mailNo, "yuntuexpress");
						//$arr_post_data["print_img"] = $rsdbts[0];
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    //$path_img_label = dirname(__FILE__) . "/../../".$rsdbts[0];
                }**/

                //更新db_order_list表
                $update_order = "";
                $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
                $update_order["shipping_time"] = time();				//交运时间
                 //$update_order["shipping_name"] = "UPS";
                //$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='UPS'");
                $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
                $update_order["shipping_name"] = $rsdb['deliver'];
                //$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'"); 放到前面
                $update_order["shipping_id"] = $shipping["id"];
                //$update_order["shipping_expectfee"] = ""; 需要通过计算
                $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
                //var_dump($arr_body_express);exit;
                //更新日志记录
                $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid'].",运单号为".$arr_post_data['mailNo'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
            }else{
                $reasonMessage = $arr_body_express['ResultDesc']; //获取返回的错误信息
                if(isset($arr_body_express['Item'][0]->Feedback)){
                    $reasonMessage.=$arr_body_express['Item'][0]->Feedback;
                }
                if(isset($arr_body_express['Item'][0]->WayBillNumber)&&$arr_body_express['Item'][0]->WayBillNumber){
                    $reasonMessage.="运单号：".$arr_body_express['Item'][0]->WayBillNumber;
                }
                //更新马帮表
                $exememo = '交运失败';
                $arr_post_data["isexe"] = 2;
                $exememo.='<br>'.$reasonMessage;
                $arr_post_data['exememo'] = $exememo;
                // echo $reasonMessage;exit;
            }
            $arr_post_data["mailinstime"] =time();
            $this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
            $str = $rsdb["orderID"].$exememo;
            return array('str'=>$str);

    }
    /********************************************
     * 欧速通交运
     **string
     ***********************************************/
    public function getostexpress()
    {
        $apiToken = "ZnVtYW5fU0hBOmZ1bWFuX1NIQTg4OA=="; //正式环境
        //$apiToken = "U1B0ZXN0MTpTUDAwMQ==";//测试环境
        //根据令牌交运
        $where  = "isexe = 0 AND orderType =13";
        $this->db->where($where);
        $total = $this->db->count_all_results('db_mabangorder');
        if($total==0)
        {
            echo "交运完成！";
            echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/13 \">";
            exit;
        }
        $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =13 ORDER BY id DESC");
        $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
        $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
        $goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B on A.goods_id = B.goods_id left join db_goods C on A.goods_id = C.goods_id"," AND A.order_id='".$orderID["order_id"]."'"." GROUP BY A.rec_id ");
        //var_dump($goodslist);exit;
        //定义数组
        $arr_json_postdata = array(); //需要传递过去的json数据
        //请求相关参数 含方法 数据等 post方式
        $headers = array("Authorization:basic {$apiToken}","Accept: text/json; charset=utf-8","Content-Type: text/json; charset=utf-8");
        $req_url = 'http://order.sprintpack.com.cn/api/CreateParcels'; //申请运单号请求路径
        $deliver_code = "";
        $rsdb['deliver'] = trim($rsdb['deliver']);
        if($rsdb['deliver']=="英伦速邮（普货）"){
            $deliver_code = "44";
            $ParcelType = "普货";
        }
        if($rsdb['deliver']=="英伦速邮全追踪（普货）"){
            $deliver_code = "66";
            $ParcelType = "普货";
        }
        //订单信息
        $arr_order['ProductType'] = $deliver_code;
        $arr_order['ParcelType'] = $ParcelType; //no

        $arr_order['OrderNumber'] = $orderID['order_sn'];
        $arr_order['ProductBarcode'] = ""; //
        $arr_order['RecipientName'] = $orderID['consignee'];

        $arr_order['RecipientAddress'] = $rsdb['customeraddress'];
        $arr_order['RecipientCity'] = $rsdb['customercity'];
        $arr_order['RecipientZipCode'] = $rsdb["customerzipcode"];
        $arr_order['RecipientState'] = $rsdb["customerprovince"]; //非必须
        $arr_order['RecipientCountry'] = $rsdb['customerqq'];//非必须
        $arr_order['PhoneNumber'] = $orderID['mobile']?$orderID['mobile']:$orderID['tel']; //非必须
        $arr_order['RecipientEmail'] = "";//非必须
        $arr_order['WeightUOM'] = "KG";
        //产品信息
        $number = 0;
        $sku_num = 0;
        foreach($goodslist as $key=>$rs)
        {
            if(!$rs['en_goods_name']){
                $rs['en_goods_name'] = "costume accessory";
            }
            $arr_order['Customs'][$key]['SKU'] = $rs['goods_sn'];
            $arr_order['Customs'][$key]['ChineseContentDescription'] = $rs['goods_name'];
            $arr_order['Customs'][$key]['EnglishContentDescription'] = $rs["en_goods_name"];
            $arr_order['Customs'][$key]['ItemCount'] = $rs['goods_number'];
            $arr_order['Customs'][$key]['ItemValue'] = 6; //固定
            $arr_order['Customs'][$key]['Currency'] = "USD";
            $arr_order['Customs'][$key]['ItemWeight'] = 0.4;
            $arr_order['Customs'][$key]['WeightUOM'] = "KG";
            $arr_order['Customs'][$key]['ItemHScode'] = "69139000000000";
            $number = $number+$rs["goods_number"];
            $sku_num = $sku_num+1;
        }
        //如果商品数量超过十个的话，每一个申报1美金
        if($number>=4){
            $unit_price = round(19/$number,2);
            $unit_weight= round(1.9/$number,2);
            foreach($goodslist as $key=>$rs)
            {
                if(!$rs['en_goods_name']){
                    $rs['en_goods_name'] = "costume accessory";
                }
                $arr_order['Customs'][$key]['SKU'] = $rs['goods_sn'];
                $arr_order['Customs'][$key]['ChineseContentDescription'] = $rs['goods_name'];
                $arr_order['Customs'][$key]['EnglishContentDescription'] = $rs["en_goods_name"];
                $arr_order['Customs'][$key]['ItemCount'] = $rs['goods_number'];
                $arr_order['Customs'][$key]['ItemValue'] = $unit_price; //固定
                $arr_order['Customs'][$key]['Currency'] = "USD";
                $arr_order['Customs'][$key]['ItemWeight'] = $unit_weight;
                $arr_order['Customs'][$key]['WeightUOM'] = "KG";
                $arr_order['Customs'][$key]['ItemHScode'] = "69139000000000";
                //$number = $number+$rs["goods_number"];
                //$sku_num = $sku_num+1;
            }
        }
        $json_post = json_encode($arr_order);
       // echo $json_post;exit;

        //获取请求的数据结果
        $json_body_express = $this->sendCurlPostRequest($req_url,$json_post,$headers);
        $arr_body_express = (array) json_decode($json_body_express);

       // print_r($arr_body_express);exit;

        /**
        if(isset($arr_body_express['model'])&&count($arr_body_express['model'])>0){
            $arr_order['OrderNumber'] = $orderID['order_sn']."-".rand(111111,999999);
            $json_post = json_encode($arr_order);
            $json_body_express = $this->sendCurlPostRequest($req_url,$json_post,$headers);
            $arr_body_express = (array) json_decode($json_body_express);
            if(isset($arr_body_express['ProductBarcode'])&&$arr_body_express['ProductBarcode']){
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $orderID['order_id'];	//订单ID db_order_list 就是tradeid
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 6;
                $imgdata["content"] = '二次交运,交易ID='.$arr_order['OrderNumber'].",运单号=".$arr_body_express['ProductBarcode'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
            }

        }**/
        //print_r($arr_body_express);exit;
        //返回值处理  交运单号
        if(isset($arr_body_express['ProductBarcode'])&&$arr_body_express['ProductBarcode']){
            $arr_post_data['exememo'] = '交运成功';
            $arr_post_data['mailNo'] = $arr_body_express['ProductBarcode']; //运单号
            $arr_post_data["isexe"] = 1;
            $arr_post_data["originCode"] = 0;
            $arr_post_data["destCode"] = 0;
            //标签地址
            //$arr_post_data['mailNo'] = '0B0480284000021405178 ';
            //标签地址
            $headers = array("Authorization:basic {$apiToken}","Content-Type: text/json; charset=utf-8");
            $label_return_url = "http://order.sprintpack.com.cn/api/CreateParcels?ProductType={$deliver_code}&productBarcode={$arr_post_data['mailNo']}"; //标签获取地址
            $content = $this->sendCurlGetRequest($label_return_url,$headers);

            $dir = dirname(__FILE__) . "/../../"."uploads/ostongexpress/".date("Ymd");
            !is_dir($dir) && @mkdir($dir, 0755, true);
            $Path_mailNo = $dir. "/".$arr_post_data['mailNo']."-".time().".pdf";
            //对获取的pdf流进行处理 标签

            //$content=file_get_contents($label_url);
            if(file_put_contents($Path_mailNo, $content)>0){
                $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                //实现pdf转换为png图片格式 放到线上做测试
                $rsdbts = $this->pdf2png($Path_mailNo, "ostexpress");
                //可能不止一张图片
                if(!empty($rsdbts[0])){
                    $image_urls=implode(",",$rsdbts);
                    // $arr_post_data["print_img"] = $image_urls;
                }else{
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    $image_urls = $rsdbts[0];
                }
                $arr_post_data["print_img"] = $image_urls;
            }
            //更新db_order_list表
            $update_order = "";
            $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
            $update_order["shipping_time"] = time();				//交运时间
            //$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
            $update_order["shipping_name"] = "欧速通英伦速邮";
            $update_order["shipping_id"] = 58;
            $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
            //var_dump($arr_body_express);exit;
            //更新日志记录
            $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
            $imgdata["updatetime"] = date("Y-m-d H:i:s");
            $imgdata["createUid"] = $_COOKIE['userid'];
            $imgdata["types"] = 3;
            $imgdata["content"] = '欧速通物流交运成功,交易ID='.$orderID['tradeid'].",运单号为".$arr_post_data['mailNo'];
            $imgdata["createUser"] =$_COOKIE['username'];
            $this->db->insert('db_goods_log', $imgdata);
        }else{
            $reasonMessage = ""; //获取返回的错误信息
            //更新马帮表
            $exememo = '交运失败';
            $arr_post_data["isexe"] = 2;
            $exememo.='<br>'.$reasonMessage;
            $arr_post_data['exememo'] = $exememo;
            // echo $reasonMessage;exit;
        }
        $arr_post_data["mailinstime"] =time();
        $this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
        $str = $rsdb["orderID"].$exememo;
        return array('str'=>$str);

    }
    /********************************************
     * 燕文交运
     **string
     ***********************************************/
    public function getyanwenexpress()
    {
        if($this->config->item("yanwenexpressset")){
            $yanwen = stripslashes($this->config->item("yanwenexpressset"));
            $arr_yanwen = unserialize($yanwen);
        }else{
            echo "未正常获得到燕文接口，请在订单相关设置中检查是否正确！";
            exit;
        }
        //暂时先测试  燕文交运相关参数
        //$url = "http://online.yw56.com.cn/service";  //production 正式环境
         //获取api令牌
         $userid = $arr_yanwen['yanwen_userid'];  //$userid = '100000'; 测试
         $password = $arr_yanwen['yanwen_pass']; //$password = '12345678' 测试
         $base_url=$arr_yanwen['yanwen_apiurl'];//$base_url = "http://online.yw56.com.cn:800/service_sandbox";  //测试地址
         //正式账号
         //$userid="205246";
         //$password="cosplaysky2013";
         //$base_url="HTTP://ONLINE.YW56.COM.CN/SERVICE";
         $url_user = $base_url."/Users/{$userid}";  //含账号密码
         $get_token_url = $base_url."/Common/LoginUser/{$userid}/{$password}";
         $xml = $this->sendCurlGetRequest($get_token_url,$token="");
         $xml_token = simplexml_load_string($xml,NULL,LIBXML_NOCDATA);
         $arr_token =json_decode(json_encode($xml_token),true);
        if(isset($arr_token['User']['ApiToken'])&&!empty($arr_token['User']['ApiToken'])){
            $apiToken = $arr_token['User']['ApiToken'];
            //根据令牌交运
            $where  = "isexe = 0 AND orderType =7";
            $this->db->where($where);
            $total = $this->db->count_all_results('db_mabangorder');
            if($total==0)
            {
                echo "交运完成！";
                echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/emsexpress/7 \">";
                die;
            }
            $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =7 ORDER BY id DESC");
            if($rsdb['isform']==1){
                $goodslist = $this->db->get_where('db_mabangsell',"orderid ='".$rsdb["orderID"]."'")->result_array();
                if(count($goodslist)>0){
                    $weight=0;
                    foreach($goodslist as $key=>$goods){
                        $goodslist[$key]['goods_number']= $goods['ordernum'];
                        $goodslist[$key]['goods_sn']= $goods['productid'];
                        $goodslist[$key]['positions']= $goods['locationad'];
                        $goodslist[$key]['goods_name']= $goods['productname'];
                        $weight +=$goods['weight'];
                    }
                }
                $weight = $weight?$weight:400;
                $weight = $weight / 1000;

            }else{
                $orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
                //$goodslist = $this->db->get_where('db_order_sell',"order_id ='".$orderID["order_id"]."'")->result_array();
                $goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B on A.goods_id = B.goods_id"," AND A.order_id='".$orderID["order_id"]."'"." GROUP BY A.rec_id ");
                foreach($goodslist as $ka=>$va){
                    $sku_many = $va['goods_sn'];
                    $goods = $this->fun->getdatabaseslist('db_goods'," AND goods_id='".$va["goods_id"]."'");
                    if($goods[0]['goods_name']){
                        $goodslist[$ka]["goods_name"] = $goods[0]['goods_name']; //获取这个goods_name
                    }
                }
            }
            $weight = 0;
            //请求相关参数 含方法 数据等 post方式
            $headers = array("Authorization: basic {$apiToken}","Content-Type: text/xml; charset=utf-8");
            $req_url = $url_user."/Expresses"; //新建快件请求路径
            //手机必须为10位纯数字（如果填写的话）
            $mobile = str_replace("-","",$rsdb['customertel1']);
            $mobile = str_replace(" ","",$mobile);
            $tel = str_replace("-","",$rsdb['customertel2']);
            $tel = str_replace(" ","",$tel);
            if(strlen($mobile)){
                $mobile = substr($mobile,-10);
            }
            if(strlen($tel)){
                $tel = substr($tel,-10);
            }
            $rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
            $straddress = strlen($rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("&"," ",$rsdb["customeraddress"]);
            $rsdb["customeraddress"] = str_replace("\n","",$rsdb["customeraddress"]);
            //$rsdb["customeraddress"] = str_replace(","," ",$rsdb["customeraddress"]);
            if($straddress<=46)
            {
                $address1 = $rsdb["customeraddress"];
                $address2 = "";
            }else{
                $address1 = substr($rsdb["customeraddress"],0,46);
                $address2 = substr($rsdb["customeraddress"],46); //只能截取
               // $address3 = substr($rsdb["customeraddress"],92,138);
            }
            if(isset($orderID['email'])){
            }else{
                $orderID['email'] = "";
            }
            $country = "";
            if($rsdb['customercountry']=="russianfederation" || $rsdb['customerqq']=="RU"){
                $country = "RUSSIAN FEDERATION";
            }
            if($rsdb['customercountry']=="costarica"){
                $country = "COSTA RICA";
            }
            if($rsdb['customercountry']=="newzealand"){
                $country = "NEW ZEALAND";
            }
            if($rsdb['customercountry']=="southafrica"){
                $country = "SOUTH AFRICA";
            }
            if($rsdb['customercountry']=="saudiarabia"){
                $country = "SAUDI ARABIA";
            }
            if($rsdb['customercountry']=="kuwati"){
                $country = "KUWAIT";
            }
            if($rsdb['customercountry']=="republicofkorea" || $rsdb['customerqq']=="KR"){
                $country = "REPUBLIC OF KOREA";
            }
            if($rsdb['customercountry']=="the republic of croatia" || $rsdb['customerqq']=="HR"){
                $country = "CROATIA";
            }
            if($rsdb['customercountry']=="bruneidarussalam" || $rsdb['customerqq']=="BN"){
                $country = "BRUNEI DARUSSALAM";
            }
            if($rsdb['customercountry']=="brasil" || $rsdb['customerqq']=="BR"){
                $country = "BRAZIL";
            }
            if($rsdb['customercountry']=="srilanka" || $rsdb['customerqq']=="LK"){
                $country = "SRI LANKA";
            }
            if($rsdb['customercountry']=="great britain" || $rsdb['customerqq']=="UK"){
                $country = "UNITED KINGDOM";
            }
            if($rsdb['customercountry']=="moldova republicof" || $rsdb['customerqq']=="MD"){
                $country = "MOLDOVA";
            }
            if($rsdb['customercountry']=="IDN" || $rsdb['customerqq']=="ID"){
                $country = "INDONESIA";
            }
            if($rsdb['customercountry']=="dominicanrepublic" || $rsdb['customerqq']=="DO"){
                $country = "DOMINICAN REPUBLIC";
            }
            if($rsdb['customercountry']=="kampuchea cambodia" || $rsdb['customerqq']=="KH"){
                $country = "CAMBODIA";
            }
            if($rsdb['customercountry']=="bosnia herzegovina" || $rsdb['customerqq']=="BA"){
                $country = "BOSNIA AND HERZEGOVINA";
            }
            if($rsdb['customercountry']=="the netherlands" || $rsdb['customerqq']=="NL"){
                $country = "NETHERLANDS";
            }
            if($rsdb['customercountry']=="Unitedemirates" || $rsdb['customerqq']=="AE"){
                $country = "United Arab Emirates";
            }
            if($rsdb['customercountry']=="Swiss" || $rsdb['customerqq']=="CH"){
                $country = "SWITZERLAND";
            }
            if($rsdb['customercountry']=="hongkong" || $rsdb['customerqq']=="HK"){
                $country = "HONG KONG";
            }
            if($rsdb['customercountry']=="reunion" || $rsdb['customerqq']=="RE"){
                $country = "REUNION ISLAND";
            }
            if($rsdb['customercountry']=="byelorussia" || $rsdb['customerqq']=="BY"){
                $country = "BELARUS";
            }
            if($rsdb['customercountry']=="Burma" || $rsdb['customerqq']=="MM"){
                $country = "MYANMAR";
            }
            if(!empty($country)){
            }else{
                $country = $rsdb['customercountry'];
            }
            //省份为空的时候，用城市 俄罗斯
            if(!empty($rsdb["customerprovince"])){
                if(strlen($rsdb["customerprovince"])>40){
                    $customerprovince = $rsdb["customercity"];
                }else{
                    $customerprovince = $rsdb["customerprovince"];
                }
            }else{
                $customerprovince = $rsdb["customercity"];
            }

            //channel 中邮上海平邮小包   中邮上海挂号小包  两种为固定的
            $xml_body="<ExpressType><Epcode></Epcode><Userid>{$userid}</Userid><Channel>{$rsdb['deliver']}</Channel><UserOrderNumber>{$rsdb['orderID']}</UserOrderNumber><SendDate></SendDate>";
            $xml_body.= " <Receiver><Userid>{$userid}</Userid><Name>{$orderID['consignee']}</Name>".
                        "<Phone>{$tel}</Phone><Mobile>{$mobile}</Mobile><Email>{$orderID['email']}</Email>".
                        "<Company>无</Company><Country>{$country}</Country><Postcode>{$rsdb["customerzipcode"]}</Postcode>".
                        "<State>{$customerprovince}</State><City>{$rsdb['customercity']}</City><Address1>$address1</Address1>".
                        "<Address2>$address2</Address2></Receiver>";
            $number = 0;
            foreach($goodslist as $key=>$rs)
            {
                if( $rs["goods_weight"]==0)
                {
                    $rs["goods_weight"] = 400;//400克
                }
                //$weightst = ($rs["goods_number"] * $rs["goods_weight"])*1000; //重量必须使用克作为单位，且不能有小数
                //$weight= $weight+$weightst;
                //$weight=ceil($weight);
                //重量固定400 单位克，不能有小数
                $weight=400;
                if($rsdb['moneytype']=="US"){
                    $moneytype = "USD";
                }elseif($rsdb['moneytype']=="RMB"){
                    $moneytype = "CNY";
                }else{
                    $moneytype = "USD"; //默认美金
                }
                //英文名，换成sku+仓位
                $cangwei = $rs['goods_sn']."    ".$rs['positions'];
                $goods_name = mb_substr($rs['goods_name'],0,18)."\n".mb_substr($rs['goods_name'],19);
                $goods_name = str_replace("&","",$goods_name);
                $xml_body.="<GoodsName><Userid>{$userid}</Userid><NameCh>$goods_name</NameCh>".
                    "<NameEn>{$cangwei}</NameEn><Weight>{$weight}</Weight><DeclaredValue>10</DeclaredValue>".
                    "<DeclaredCurrency>{$moneytype}</DeclaredCurrency></GoodsName>";
                $number = $number+$rs["goods_number"];
            }
            if(isset($orderID['remark'])){
                $xml_body.="<Memo>{$orderID['remark']}</Memo><Quantity>{$number}</Quantity>";
            }else{
                $xml_body.="<Memo></Memo><Quantity>{$number}</Quantity>";
            }

            $xml_body.="</ExpressType>";
            //header("Content-type:text/xml");
            //echo $xml_body;exit;
            //获取请求的数据结果
            $xml_body_express = $this->sendCurlPostRequest($req_url,$xml_body,$headers);
            $xml_body_express = simplexml_load_string($xml_body_express,NULL,LIBXML_NOCDATA);
            $arr_body_express =json_decode(json_encode($xml_body_express),true);
            // 重复订单号交运时执行更换订单号操作 date 2017/8/12   [Reason] => V121 [ReasonMessage] => 您的订单号不可重复
            if(isset($arr_body_express['CallSuccess'])&&$arr_body_express['CallSuccess']=="false"&&$arr_body_express['Response']['Reason']=="V121"){
                $arr_order['OrderNumber'] = $orderID['order_sn']."-".rand(111111,999999);
                $xml_body = str_replace("<UserOrderNumber>{$rsdb['orderID']}</UserOrderNumber>","<UserOrderNumber>{$arr_order['OrderNumber']}</UserOrderNumber>",$xml_body);
                $xml_body_express = $this->sendCurlPostRequest($req_url,$xml_body,$headers);
                $xml_body_express = simplexml_load_string($xml_body_express,NULL,LIBXML_NOCDATA);
                $arr_body_express =json_decode(json_encode($xml_body_express),true);
                if(isset($arr_body_express['CallSuccess'])&&$arr_body_express['CallSuccess']=="true"){
                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $orderID['order_id'];	//订单ID db_order_list 就是tradeid
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 6;//二次交运
                    $imgdata["content"] = '二次交运,交易ID='.$arr_order['OrderNumber'].",运单号=".$arr_body_express['CreatedExpress']['Epcode'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);
                }
                //print_r($arr_body_express);exit;
            }
             //返回值处理  交运单号
            if(isset($arr_body_express['CallSuccess'])&&$arr_body_express['CallSuccess']=="true"){
                $createDate = date("Y-m-d H:i:s",strtotime($arr_body_express['CreateDate']));
                $arr_post_data['exememo'] = '交运成功';
                $arr_post_data['mailNo'] = $arr_body_express['CreatedExpress']['Epcode']; //运单号
                $mailNo = $arr_body_express['CreatedExpress']['Epcode'];  //$mailNo = 'YE880013095CN';
                $arr_post_data["isexe"] = 1;
                $arr_post_data["originCode"] = 0;
                $arr_post_data["destCode"] = 0;
                //测试数据
                /**
                 * 各种运单号类型，大小
                 * {LabelSize}：标签大小。支持的值为：A4L, A4LI, A4LC, A4LCI, A6L, A6LI, A6LC, A6LCI, A10x10L, A10x10LI,
                 *   A10x10LC, A10x10LCI。
                 *(注：L为运单，C为报关签条，I为拣货单。)
                 */
                //运单号
                //$label_url = $url_user."/expresses/{$mailNo}/A10x10LLabel"; //运单
                //$rs_label = $this->sendCurlGetRequest($label_url,$headers);
                //运单号含报关签条
                $label_url_declare = $url_user."/expresses/{$mailNo}/A10x10LCLabel"; //报关
                $rs_label_declare = $this->sendCurlGetRequest($label_url_declare,$headers);
                //$label_url_declare = "http://Online.yw56.com.cn:800/service_sandbox/Users/100000/Expresses/RG906964838CN/A10x10LCLabel";
                //$rs_label_declare = $this->sendCurlGetRequest($label_url_declare,$headers);

                //对获取的pdf流进行处理 标签
                $dir = dirname(__FILE__) . "/../../uploads/yanwenexpress/".date("Ymd");
                !is_dir($dir) && @mkdir($dir, 0755, true);
                //$Path_mailNo = $dir. "/".$mailNo."_mailno.pdf";
                $Path_declare = $dir. "/".$mailNo."_declare.pdf";
                //$content_mailno=$rs_label;
                $content_declare=$rs_label_declare;
                $path_img_label = "";
                /**
                if(file_put_contents($Path_mailNo, $content_mailno))
                {
                   $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_mailNo);
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                   $rsdbts = $this->pdf2png($Path_mailNo,"yanwenexpress"); //转为对应目录下存储
                   //$arr_post_data["print_img"] = $rsdbts[0];
                    $path_img_label = dirname(__FILE__) . "/../../".$rsdbts[0];

                }**/
                //$path_img_declare = "";
                if(file_put_contents($Path_declare, $content_declare))
                {
                    $pathst = str_replace(dirname(__FILE__) . "/../../", '',$Path_declare);
                    $arr_post_data["printUrl"] = $pathst;  //pdf格式文件地址
                    //$arr_post_data["printUrl_declare"] = $pathst;  //pdf格式文件地址
                    //实现pdf转换为png图片格式 放到线上做测试
                    $rsdbts = $this->pdf2png($Path_declare,"yanwenexpress");
                    //$arr_post_data["print_img"] = $rsdbts[0];
                    //$path_img_declare = dirname(__FILE__) . "/../../".$rsdbts[0];
                    //可能不止一张图片
                    if(!empty($rsdbts[0])){
                        $image_urls=implode(",",$rsdbts);
                       // $arr_post_data["print_img"] = $image_urls;
                    }else{
                        //$arr_post_data["print_img"] = $rsdbts[0];
                        $image_urls = $rsdbts[0];
                    }
                }
                //手动写面单 配货单（如果多于一种的话)
                /**  html页面生成
                if(count($goodslist)>1){
                    //配货单测试
                    //拼接字符串生成html文件
                    $html = "<html><head><title></title><style rel='stylesheet'>table{margin:0;padding:0;border-collapse:collapse;}table tr{margin:0;padding:0;border-collapse:collapse;}table tr td{margin:0;padding:0;border-collapse: collapse;}</style> </head><body style='margin:0;padding:0;'>";
                    $html.="<table style='width: 100mm;height: 100mm;margin:0;padding:0;'>";
                    if(count($goodslist)>0){
                        foreach ($goodslist as $k=>$v){
                            $cangwei = $v['positions']; //仓位
                            if(empty($cangwei)){
                                $cangwei = "null";
                            }
                            $html.="<tr><td style='font-size:10px;'>Costume accessories</td><td style='font-size:10px;'>(".$v['goods_name']."【".$v['goods_sn']."_".$cangwei."*".$v['goods_number']."】)"."</td></tr>";
                        }
                    }
                    $html.="</table>";
                    $html.="</body></html>";
                    $dir_pdf = dirname(__FILE__) . "/../../uploads/yanwenexpress/".date("Ymd");
                    !is_dir($dir_pdf) && @mkdir($dir_pdf, 0755, true);
                    file_put_contents($dir_pdf."/"."yanwen.html",$html); //内容写入文件
                    $html_path = $dir_pdf."/"."yanwen.html";
                    //生成pdf文件，并保存至相关目录
                    $rs_pdf_filename = $this->html2pdf($html_path,$dir_pdf); //返回文件名
                    $pdf_path = $dir_pdf."/".$rs_pdf_filename; //配货单
                    $rsdbts = $this->pdf2png($pdf_path,"yanwenexpress");
                    $image_urls = $image_urls.",".$rsdbts[0];
                }
                 **/
                $arr_post_data["print_img"] = $image_urls;
                /**
                $label_path = $this->writeTwoImgs($path_img_declare,$path_img_label,$mailNo);
                if($label_path){
                    $path = str_replace(dirname(__FILE__) . "/../../", '', $label_path);
                    $arr_post_data["print_img"] = $path;
                }**/
                if($rsdb['deliver']=="中邮上海挂号小包"){
                    $rsdb['deliver'] = "中邮小包挂";
                }
                /**弃用 改为 新加坡邮政挂号小包
                if($rsdb['deliver']=="荷兰邮政挂号小包(不含电)"){
                    $rsdb['deliver'] = "荷兰邮政挂号小包";
                }**/
                $update_order = "";
                $update_order["shipping_number"] = $arr_post_data['mailNo'];	//运单号
                $update_order["shipping_time"] = time();				//交运时间
                $update_order["shipping_name"] = $rsdb['deliver'];
                $shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='{$rsdb['deliver']}'");
                $update_order["shipping_id"] = $shipping["id"];
                //$update_order["shipping_expectfee"] = ""; 需要通过计算
                $this->db->update('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]);
                    //var_dump($arr_body_express);exit;
                //更新日志记录
                if(isset($orderID["order_id"])){
                    $imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid'].",运单号为".$arr_post_data['mailNo'];
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);
                }
            }else{
                $reasonMessage = $arr_body_express['Response']['ReasonMessage']; //获取返回的错误信息
                //更新马帮表
                $exememo = '交运失败';
                $arr_post_data["isexe"] = 2;
                $exememo.='<br>'.$reasonMessage;
                $arr_post_data['exememo'] = $exememo;
               // echo $reasonMessage;exit;
            }
                $arr_post_data["mailinstime"] =time();
                $this->db->query($this->db->update_string('db_mabangorder', $arr_post_data, 'id=' .$rsdb["id"]));
                $str = $rsdb["orderID"].$exememo;
                return array('str'=>$str);
        }

    }
    //过滤所有特殊字符
    private function strFilter($str){
        $str = str_replace('`', '', $str);
        $str = str_replace('·', '', $str);
        $str = str_replace('~', '', $str);
        $str = str_replace('!', '', $str);
        $str = str_replace('！', '', $str);
        $str = str_replace('@', '', $str);
        $str = str_replace('#', '', $str);
        $str = str_replace('$', '', $str);
        $str = str_replace('￥', '', $str);
        $str = str_replace('%', '', $str);
        $str = str_replace('^', '', $str);
        $str = str_replace('……', '', $str);
        $str = str_replace('&', '', $str);
        $str = str_replace('*', '', $str);
        $str = str_replace('(', '', $str);
        $str = str_replace(')', '', $str);
        $str = str_replace('（', '', $str);
        $str = str_replace('）', '', $str);
        $str = str_replace('-', '', $str);
        $str = str_replace('_', '', $str);
        $str = str_replace('——', '', $str);
        $str = str_replace('+', '', $str);
        $str = str_replace('=', '', $str);
        $str = str_replace('|', '', $str);
        $str = str_replace('\\', '', $str);
        $str = str_replace('[', '', $str);
        $str = str_replace(']', '', $str);
        $str = str_replace('【', '', $str);
        $str = str_replace('】', '', $str);
        $str = str_replace('{', '', $str);
        $str = str_replace('}', '', $str);
        $str = str_replace(';', '', $str);
        $str = str_replace('；', '', $str);
        $str = str_replace(':', '', $str);
        $str = str_replace('：', '', $str);
        $str = str_replace('\'', '', $str);
        $str = str_replace('"', '', $str);
        $str = str_replace('“', '', $str);
        $str = str_replace('”', '', $str);
        $str = str_replace(',', '', $str);
        $str = str_replace('，', '', $str);
        $str = str_replace('<', '', $str);
        $str = str_replace('>', '', $str);
        $str = str_replace('《', '', $str);
        $str = str_replace('》', '', $str);
        $str = str_replace('.', '', $str);
        $str = str_replace('。', '', $str);
        $str = str_replace('/', '', $str);
        $str = str_replace('、', '', $str);
        $str = str_replace('?', '', $str);
        $str = str_replace('？', '', $str);
        return trim($str);
    }
    //通过html制作pdf文件，然后生成图片文件
    protected function html2pdf($html_file,$dir_pdf){
        include_once APPPATH.'/../fuman/mpdf60/mpdf.php';
        $mpdf=new mPDF('zh-CN');
        //设置字体,解决中文乱码
        $mpdf->useAdobeCJK = true;
        //获取要生成的静态文件
        //$url = APPPATH.'../public/index.php';
         $url = $html_file;
         $html=file_get_contents($url);
        //设置pdf显示方式
        $mpdf->SetDisplayMode('fullpage');
        //设置pdf的尺寸为100mm*100mm
        $mpdf->WriteHTML('<pagebreak sheet-size="100mm 100mm" />');
        //创建pdf文件
        $mpdf->WriteHTML($html);
        //删除pdf第一页(由于设置pdf尺寸导致多出了一页)
        $mpdf->DeletePages(1,1);
        //输出pdf
        //$path = APPPATH.'../public/';
        $path = $dir_pdf."/";
        $pdf_name = md5(time()).'.pdf';
        $mpdf->Output($path.$pdf_name);
        return $pdf_name; //返回pdf文件名
    }
    //图片合并 物流标签与报关标签
    //$path_img_lable 标签图片  $path_img_declare报关图片
    private function writeTwoImgs($path_img_lable,$path_img_declare,$mailNo){
        $pic_lable = $path_img_lable;
        $pic_lable_two = $path_img_declare;
        if(is_file($pic_lable)&&is_file($pic_lable_two)){
            $im = new imagick();
            // 获取图片宽x高
            $im->readImage($pic_lable);
            $geo = $im->getImageGeometry();
            $width = $geo['width'];
            $height = $geo['height']*2;
            $im->newimage($width,$height, 'white');
            $im->setimageformat('png');
            $canvas = new imagick($pic_lable);
            $im->compositeimage($canvas, Imagick::COMPOSITE_OVER,0, 0);
            $canves= new imagick($pic_lable_two);
            $im->compositeimage($canves, Imagick::COMPOSITE_OVER,0, $geo['height']);
            $dir = dirname(__FILE__)."/../../uploads/yanwenexpress/".date("Ymd")."/".$mailNo.".png";
            $im->writeImage($dir);
            // 释放资源
             return $dir;
            //$im->destroy();
        }else{
            //echo 999;exit;
            return 0;
        }




    }
    /**************************
     **
     **	将PDF转换成图片
     **
     *************/
    function pdf2png($PDF,$filename="yanwenexpress"){

		/*
        if(!extension_loaded('imagick')){
            return false;
        }
        $Path1 = dirname(__FILE__). "/../../";
        $Path2 = "uploads/".$filename."/".date("Ymd");
        $Path = $Path1.$Path2;
        !is_dir($Path) && @mkdir($Path, 0755, true);
        if(!file_exists($PDF)){
            return false;
        }
        $IM =new imagick();
        $IM->setResolution(300,300);
        $IM->setCompressionQuality(100);
        // $IM->thumbnailImage(600,8);

        $IM->readImage($PDF);
        foreach($IM as $Key => $Var){
            $Var->setImageFormat('jpg');
			$ors=rand(1000,9999).substr(time(),-5).substr(microtime(),2,5);
            $finame = '/'.$ors.md5($Key.time()).'.jpg';

            $Filename = $Path.$finame;
            if($Var->writeImage($Filename)==true){
                $Return[]= $Path2.$finame;
            }
        }*/
		return $this->fun->pdf2png($PDF,$filename);
       // var_dump($Return);exit;
        return $Return;
    }
    function saveexpress()
    {
        $postdata="";
        //YT 云途   YW 燕文
        $express_type=array('UPS'=>2,'DHL'=>3,'CNE'=>4,'UBI'=>5,'YT'=>6,'YW'=>7,'EMS'=>8,'CNPOST'=>11,"OST"=>13);
        $orderlist = trim($this->input->post('yanwenorderlist'));
        if(!$orderlist)
        {
            $this->fun->phpalert(2, "请输入订单号");
            die;
        }
        $post_express_type=$this->input->post('yanwentype');
        $orderType=$express_type[$post_express_type];
		
        $orderlist = substr($orderlist,0,-1);
        $orderdata = implode("','",explode(",",$orderlist));	//替换字符
        $data = $this->db->get_where("db_order_list","order_sn in ('".$orderdata."')")->result_array();
		
        $insert_data=array();//存储已经正确的需要做交运的mabang订单id
        if(count($data)>0){
            foreach($data as $key=>$rs){
                //必须都是已配货状态
                /*
                foreach($data as $key=>$res)
                {
                    $status[] = $res["order_status"];
                }
                $status = array_unique($status);
                if(count($status)>1) //去重复后，大于1个元素
                {
                    die("存在不同的订单状态");
                }else{
                    if($status[0] !=3)
                    {
                        //die("不是配货中状态");
                    }

                }*/

                $rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE orderID='".trim($rs["order_sn"])."' AND orderType ='".$orderType."'");
                if($rsdb)
                {
                    $thi1orderid = $rsdb["id"];
                }else{
                    $thi1orderid = 0;
                }

                if( $rs["tel"]=='' &&  $rs["mobile"] =='null')
                {
                    $rs["tel"] = '00000000';
                }

                switch ($rs["order_status"]) {
                    case 1;
                        $statustext = '新订单';
                        break;
                    case 2:
                        $statustext  = '已支付';
                        break;
                    case 3:
                        $statustext  = '配货中';
                        break;
                    case 4:
                        $statustext  = '已发货';
                        break;
                    case 5:
                        $statustext  = '已完成';
                        break;
                    case 6:
                        $statustext  = '已作废';
                        break;
                    case 7:
                        $statustext  = '待审查';
                        break;
                }
				$postdata="";
                $postdata["orderType"] = $orderType;
                $postdata["orderID"] = trim($rs["order_sn"]);
                $postdata["statusst"]=$statustext;
                $postdata["customerid"] = $rs["customerid"];
                $postdata["customertype"]= $rs["shopname"];
                $postdata["customertel1"]= $rs["tel"]?$rs["tel"]:$rs["mobile"];
                $postdata["customertel2"]= $rs["mobile"];
                //获取国家标识strtoupper
                $rscountry = $this->fun->getdatabasesdetail("d_country"," AND countrynamecn='".strtoupper(trim($rs["country"]))."'");
                if($rscountry)
                {
                    $customerqq = $rscountry["countryid"];
                }
                $postdata["customerqq"]=$rs["country_code"];	//国家标识
                $postdata["customercountry"]= $rs["country"];//国家
                $postdata["customerprovince"]= $rs["province"];
                $postdata["customercity"]= $rs["city"];
                $postdata["customeraddress"]= $rs["address"].$rs["address2"];
                $postdata["customerzipcode"]= $rs["zipcode"];
                $postdata["moneytype"]= $rs["moneytype"];
                $postdata["content1"]= NULL;
                $postdata["intime"]= date("Y-m-d H:i:s");
                $postdata["createUser"]=$_COOKIE["username"];
                //发货方式
                if($this->input->post('deliver')){
                    $postdata['deliver'] = $this->input->post('deliver');
                }
                //物流方式 只针对e邮宝线上线下
                if($this->input->post('logistics')){
                    $postdata['logistics'] = $this->input->post('logistics');
                }
                //账号 只针对e邮宝线上线下
                if($this->input->post('account')){
                    $postdata['logistics_account'] = $this->input->post('account');
                }
                if( $thi1orderid)
                {
                    $postdata["isexe"]= 0;
                    $postdata["exememo"]='重复提交订单';
                    $this->db->update('db_mabangorder', $postdata, 'id=' . $thi1orderid);

                }else{
                    $res = $this->db->query($this->db->insert_string('db_mabangorder', $postdata));
                }
            }
        }
        //return $insert_ids;
         return $orderType;
    }
    //模拟post请求
    public function sendCurlPostRequest($url,$post_data,$headers){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_URL,$url);
        if(count($headers)>0){
            curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        //var_dump($output);exit;
        curl_close($ch);
        return $output;
    }
    //模拟get请求
    public function sendCurlGetRequest($url,$headers){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_URL,$url);
        if($headers){
            curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;

    }
    //模拟CURL请求
    public function sendCurlCommonRequest($url,$method="post",$post_data,$headers){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        if(count($headers)>0){
            curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $method = strtoupper($method);
        switch ($method){
            case "GET":
                //curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
            case "PUT":
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
                break;
            case "DELETE":
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                //curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
                break;
        }
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //var_dump($output);exit;
        curl_close($ch);

        return $httpCode;
        //return $output;
    }
    /***********
     ***	处理抓取远程图片，马帮或者内部系统抓取图片都使用这个功能
     *** images_url 原远程连接
     *** local_url  抓取后存放图片
     *** thumb_url  缩略图
     **************/
    function getMabangImages($url,$parent_goods='')
    {
        $file_path = pathinfo($url);
        if($parent_goods =="")
        {
            $parent_goods = $file_path["filename"];
        }

        $ch = curl_init();
        $timeout = 10;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $contents = curl_exec($ch);
        if (preg_match("/404/", $contents)){
            return false;
        }else{
            //抓取图片
            $Path1 =dirname(__FILE__)."/../../";
            $Path2 ="uploads/emsexpress/".date("Ymd");	//存储地址
            $dir = $Path1.$Path2;
            !is_dir($dir) && @mkdir($dir, 0755, true);
            $Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
            $content=file_get_contents($url);//下载到内存
            $Path = $Path1.$Path2.$Path3;
            if(file_put_contents($Path, $content)>0)
            {
                $result_str["images_url"]= $url;
                $result_str["local_url"]= $Path2.$Path3;
                //存缩略图

                $upload_path_thumbnail = '/uploads/thumbnail/'.date("Ymd")."";
                $dirthumb = dirname(__FILE__) . "/../..".$upload_path_thumbnail;
                !is_dir($dirthumb) && @mkdir($dirthumb, 0755, true);
                if (file_exists($Path)) {
                    $this->load->library('image_lib');
                    $configimg['image_library'] = 'gd2';
                    $configimg['source_image'] =$Path;
                    $configimg['create_thumb'] = TRUE;
                    $configimg['maintain_ratio'] = TRUE;
                    $configimg['new_image'] =  $dirthumb."/". $file_path["filename"]."." . $file_path['extension'];
                    $configimg['width']     = $this->config->item('resizeToWidth');
                    $configimg['height']   = $this->config->item('resizeToHeight');
                    $this->image_lib->initialize($configimg);
                    if ( ! $this->image_lib->resize())
                    {
                        echo $this->image_lib->display_errors();
                    }else{
                        $this->image_lib->clear();
                    }
                }
                $filesize = round(filesize($Path)/1024,2)."kb";//文件大小
                $result_str["filesize"] = $filesize;
                $result_str["filename"] = $file_path["filename"];
                $result_str["thumb_url"] = $upload_path_thumbnail."/". $file_path["filename"]."_thumb." .$file_path['extension'];
            }

            return $result_str;
        }

    }
}

/* End of file Doit_m.php */